",
footer:
"",
closeButton:
"",
form:
"",
inputs: {
text:
"",
textarea:
"",
email:
"",
select:
"",
checkbox:
"",
date:
"",
time:
"",
number:
"",
password:
""
}
};
var defaults = {
locale: "en",
backdrop: "static",
animate: true,
className: null,
closeButton: true,
show: true,
container: "body"
};
var exports = {};
/**
* @private
*/
function _t(key) {
var locale = locales[defaults.locale];
return locale ? locale[key] : locales.en[key];
}
function processCallback(e, dialog, callback) {
e.stopPropagation();
e.preventDefault();
var preserveDialog = $.isFunction(callback) && callback.call(dialog, e) === false;
if (!preserveDialog) {
dialog.modal("hide");
}
}
function getKeyLength(obj) {
var k, t = 0;
for (k in obj) {
t ++;
}
return t;
}
function each(collection, iterator) {
var index = 0;
$.each(collection, function(key, value) {
iterator(key, value, index++);
});
}
function sanitize(options) {
var buttons;
var total;
if (typeof options !== "object") {
throw new Error("Please supply an object of options");
}
if (!options.message) {
throw new Error("Please specify a message");
}
options = $.extend({}, defaults, options);
if (!options.buttons) {
options.buttons = {};
}
buttons = options.buttons;
total = getKeyLength(buttons);
each(buttons, function(key, button, index) {
if ($.isFunction(button)) {
button = buttons[key] = {
callback: button
};
}
if ($.type(button) !== "object") {
throw new Error("button with key " + key + " must be an object");
}
if (!button.label) {
button.label = key;
}
if (!button.className) {
if (total <= 2 && index === total-1) {
button.className = "btn-primary";
} else {
button.className = "btn-default";
}
}
});
return options;
}
/**
* map a flexible set of arguments into a single returned object
* if args.length is already one just return it, otherwise
* use the properties argument to map the unnamed args to
* object properties
* so in the latter case:
* mapArguments(["foo", $.noop], ["message", "callback"])
* -> { message: "foo", callback: $.noop }
*/
function mapArguments(args, properties) {
var argn = args.length;
var options = {};
if (argn < 1 || argn > 2) {
throw new Error("Invalid argument length");
}
if (argn === 2 || typeof args[0] === "string") {
options[properties[0]] = args[0];
options[properties[1]] = args[1];
} else {
options = args[0];
}
return options;
}
/**
* merge a set of default dialog options with user supplied arguments
*/
function mergeArguments(defaults, args, properties) {
return $.extend(
true,
{},
defaults,
mapArguments(
args,
properties
)
);
}
/**
* this entry-level method makes heavy use of composition to take a simple
* range of inputs and return valid options suitable for passing to bootbox.dialog
*/
function mergeDialogOptions(className, labels, properties, args) {
var baseOptions = {
className: "bootbox-" + className,
buttons: createLabels.apply(null, labels)
};
return validateButtons(
mergeArguments(
baseOptions,
args,
properties
),
labels
);
}
/**
* from a given list of arguments return a suitable object of button labels
* all this does is normalise the given labels and translate them where possible
* e.g. "ok", "confirm" -> { ok: "OK, cancel: "Annuleren" }
*/
function createLabels() {
var buttons = {};
for (var i = 0, j = arguments.length; i < j; i++) {
var argument = arguments[i];
var key = argument.toLowerCase();
var value = argument.toUpperCase();
buttons[key] = {
label: _t(value)
};
}
return buttons;
}
function validateButtons(options, buttons) {
var allowedButtons = {};
each(buttons, function(key, value) {
allowedButtons[value] = true;
});
each(options.buttons, function(key) {
if (allowedButtons[key] === undefined) {
throw new Error("button key " + key + " is not allowed (options are " + buttons.join("\n") + ")");
}
});
return options;
}
exports.alert = function() {
var options;
options = mergeDialogOptions("alert", ["ok"], ["message", "callback"], arguments);
if (options.callback && !$.isFunction(options.callback)) {
throw new Error("alert requires callback property to be a function when provided");
}
/**
* overrides
*/
options.buttons.ok.callback = options.onEscape = function() {
if ($.isFunction(options.callback)) {
return options.callback.call(this);
}
return true;
};
return exports.dialog(options);
};
exports.confirm = function() {
var options;
options = mergeDialogOptions("confirm", ["cancel", "confirm"], ["message", "callback"], arguments);
/**
* overrides; undo anything the user tried to set they shouldn't have
*/
options.buttons.cancel.callback = options.onEscape = function() {
return options.callback.call(this, false);
};
options.buttons.confirm.callback = function() {
return options.callback.call(this, true);
};
if (!$.isFunction(options.callback)) {
throw new Error("confirm requires a callback");
}
return exports.dialog(options);
};
exports.prompt = function() {
var options;
var defaults;
var dialog;
var form;
var input;
var shouldShow;
var inputOptions;
form = $(templates.form);
defaults = {
className: "bootbox-prompt",
buttons: createLabels("cancel", "confirm"),
value: "",
inputType: "text"
};
options = validateButtons(
mergeArguments(defaults, arguments, ["title", "callback"]),
["cancel", "confirm"]
);
shouldShow = (options.show === undefined) ? true : options.show;
/**
* overrides; undo anything the user tried to set they shouldn't have
*/
options.message = form;
options.buttons.cancel.callback = options.onEscape = function() {
return options.callback.call(this, null);
};
options.buttons.confirm.callback = function() {
var value;
switch (options.inputType) {
case "text":
case "textarea":
case "email":
case "select":
case "date":
case "time":
case "number":
case "password":
value = input.val();
break;
case "checkbox":
var checkedItems = input.find("input:checked");
value = [];
each(checkedItems, function(_, item) {
value.push($(item).val());
});
break;
}
return options.callback.call(this, value);
};
options.show = false;
if (!options.title) {
throw new Error("prompt requires a title");
}
if (!$.isFunction(options.callback)) {
throw new Error("prompt requires a callback");
}
if (!templates.inputs[options.inputType]) {
throw new Error("invalid prompt type");
}
input = $(templates.inputs[options.inputType]);
switch (options.inputType) {
case "text":
case "textarea":
case "email":
case "date":
case "time":
case "number":
case "password":
input.val(options.value);
break;
case "select":
var groups = {};
inputOptions = options.inputOptions || [];
if (!$.isArray(inputOptions)) {
throw new Error("Please pass an array of input options");
}
if (!inputOptions.length) {
throw new Error("prompt with select requires options");
}
each(inputOptions, function(_, option) {
var elem = input;
if (option.value === undefined || option.text === undefined) {
throw new Error("given options in wrong format");
}
if (option.group) {
if (!groups[option.group]) {
groups[option.group] = $("").attr("label", option.group);
}
elem = groups[option.group];
}
elem.append("");
});
each(groups, function(_, group) {
input.append(group);
});
input.val(options.value);
break;
case "checkbox":
var values = $.isArray(options.value) ? options.value : [options.value];
inputOptions = options.inputOptions || [];
if (!inputOptions.length) {
throw new Error("prompt with checkbox requires options");
}
if (!inputOptions[0].value || !inputOptions[0].text) {
throw new Error("given options in wrong format");
}
input = $("");
each(inputOptions, function(_, option) {
var checkbox = $(templates.inputs[options.inputType]);
checkbox.find("input").attr("value", option.value);
checkbox.find("label").append(option.text);
each(values, function(_, value) {
if (value === option.value) {
checkbox.find("input").prop("checked", true);
}
});
input.append(checkbox);
});
break;
}
if (options.placeholder) {
input.attr("placeholder", options.placeholder);
}
if (options.pattern) {
input.attr("pattern", options.pattern);
}
if (options.maxlength) {
input.attr("maxlength", options.maxlength);
}
form.append(input);
form.on("submit", function(e) {
e.preventDefault();
e.stopPropagation();
dialog.find(".btn-primary").click();
});
dialog = exports.dialog(options);
dialog.off("shown.bs.modal");
dialog.on("shown.bs.modal", function() {
input.focus();
});
if (shouldShow === true) {
dialog.modal("show");
}
return dialog;
};
exports.dialog = function(options) {
options = sanitize(options);
var dialog = $(templates.dialog);
var innerDialog = dialog.find(".modal-dialog");
var body = dialog.find(".modal-body");
var buttons = options.buttons;
var buttonStr = "";
var callbacks = {
onEscape: options.onEscape
};
if ($.fn.modal === undefined) {
throw new Error(
"$.fn.modal is not defined; please double check you have included " +
"the Bootstrap JavaScript library. See http://getbootstrap.com/javascript/ " +
"for more details."
);
}
each(buttons, function(key, button) {
buttonStr += "";
callbacks[key] = button.callback;
});
body.find(".bootbox-body").html(options.message);
if (options.animate === true) {
dialog.addClass("fade");
}
if (options.className) {
dialog.addClass(options.className);
}
if (options.size === "large") {
innerDialog.addClass("modal-lg");
} else if (options.size === "small") {
innerDialog.addClass("modal-sm");
}
if (options.title) {
body.before(templates.header);
}
if (options.closeButton) {
var closeButton = $(templates.closeButton);
if (options.title) {
dialog.find(".modal-header").prepend(closeButton);
} else {
closeButton.css("margin-top", "-10px").prependTo(body);
}
}
if (options.title) {
dialog.find(".modal-title").html(options.title);
}
if (buttonStr.length) {
body.after(templates.footer);
dialog.find(".modal-footer").html(buttonStr);
}
/**
* Bootstrap event listeners; used handle extra
* setup & teardown required after the underlying
* modal has performed certain actions
*/
dialog.on("hidden.bs.modal", function(e) {
if (e.target === this) {
dialog.remove();
}
});
/*
dialog.on("show.bs.modal", function() {
if (options.backdrop) {
dialog.next(".modal-backdrop").addClass("bootbox-backdrop");
}
});
*/
dialog.on("shown.bs.modal", function() {
dialog.find(".btn-primary:first").focus();
});
/**
* Bootbox event listeners; experimental and may not last
* just an attempt to decouple some behaviours from their
* respective triggers
*/
if (options.backdrop !== "static") {
dialog.on("click.dismiss.bs.modal", function(e) {
if (dialog.children(".modal-backdrop").length) {
e.currentTarget = dialog.children(".modal-backdrop").get(0);
}
if (e.target !== e.currentTarget) {
return;
}
dialog.trigger("escape.close.bb");
});
}
dialog.on("escape.close.bb", function(e) {
if (callbacks.onEscape) {
processCallback(e, dialog, callbacks.onEscape);
}
});
/**
* Standard jQuery event listeners; used to handle user
* interaction with our dialog
*/
dialog.on("click", ".modal-footer button", function(e) {
var callbackKey = $(this).data("bb-handler");
processCallback(e, dialog, callbacks[callbackKey]);
});
dialog.on("click", ".bootbox-close-button", function(e) {
processCallback(e, dialog, callbacks.onEscape);
});
dialog.on("keyup", function(e) {
if (e.which === 27) {
dialog.trigger("escape.close.bb");
}
});
$(options.container).append(dialog);
dialog.modal({
backdrop: options.backdrop ? "static": false,
keyboard: false,
show: false
});
if (options.show) {
dialog.modal("show");
}
/*
function BBDialog(elem) {
this.elem = elem;
}
BBDialog.prototype = {
hide: function() {
return this.elem.modal("hide");
},
show: function() {
return this.elem.modal("show");
}
};
*/
return dialog;
};
exports.setDefaults = function() {
var values = {};
if (arguments.length === 2) {
values[arguments[0]] = arguments[1];
} else {
values = arguments[0];
}
$.extend(defaults, values);
};
exports.hideAll = function() {
$(".bootbox").modal("hide");
return exports;
};
/**
* standard locales. Please add more according to ISO 639-1 standard. Multiple language variants are
* unlikely to be required. If this gets too large it can be split out into separate JS files.
*/
var locales = {
bg_BG : {
OK : "Ок",
CANCEL : "Отказ",
CONFIRM : "Потвърждавам"
},
br : {
OK : "OK",
CANCEL : "Cancelar",
CONFIRM : "Sim"
},
cs : {
OK : "OK",
CANCEL : "Zrušit",
CONFIRM : "Potvrdit"
},
da : {
OK : "OK",
CANCEL : "Annuller",
CONFIRM : "Accepter"
},
de : {
OK : "OK",
CANCEL : "Abbrechen",
CONFIRM : "Akzeptieren"
},
el : {
OK : "Εντάξει",
CANCEL : "Ακύρωση",
CONFIRM : "Επιβεβαίωση"
},
en : {
OK : "OK",
CANCEL : "Cancel",
CONFIRM : "OK"
},
es : {
OK : "OK",
CANCEL : "Cancelar",
CONFIRM : "Aceptar"
},
et : {
OK : "OK",
CANCEL : "Katkesta",
CONFIRM : "OK"
},
fa : {
OK : "قبول",
CANCEL : "لغو",
CONFIRM : "تایید"
},
fi : {
OK : "OK",
CANCEL : "Peruuta",
CONFIRM : "OK"
},
fr : {
OK : "OK",
CANCEL : "Annuler",
CONFIRM : "D'accord"
},
he : {
OK : "אישור",
CANCEL : "ביטול",
CONFIRM : "אישור"
},
hu : {
OK : "OK",
CANCEL : "Mégsem",
CONFIRM : "Megerősít"
},
hr : {
OK : "OK",
CANCEL : "Odustani",
CONFIRM : "Potvrdi"
},
id : {
OK : "OK",
CANCEL : "Batal",
CONFIRM : "OK"
},
it : {
OK : "OK",
CANCEL : "Annulla",
CONFIRM : "Conferma"
},
ja : {
OK : "OK",
CANCEL : "キャンセル",
CONFIRM : "確認"
},
lt : {
OK : "Gerai",
CANCEL : "Atšaukti",
CONFIRM : "Patvirtinti"
},
lv : {
OK : "Labi",
CANCEL : "Atcelt",
CONFIRM : "Apstiprināt"
},
nl : {
OK : "OK",
CANCEL : "Annuleren",
CONFIRM : "Accepteren"
},
no : {
OK : "OK",
CANCEL : "Avbryt",
CONFIRM : "OK"
},
pl : {
OK : "OK",
CANCEL : "Anuluj",
CONFIRM : "Potwierdź"
},
pt : {
OK : "OK",
CANCEL : "Cancelar",
CONFIRM : "Confirmar"
},
ru : {
OK : "OK",
CANCEL : "Отмена",
CONFIRM : "Применить"
},
sq : {
OK : "OK",
CANCEL : "Anulo",
CONFIRM : "Prano"
},
sv : {
OK : "OK",
CANCEL : "Avbryt",
CONFIRM : "OK"
},
th : {
OK : "ตกลง",
CANCEL : "ยกเลิก",
CONFIRM : "ยืนยัน"
},
tr : {
OK : "Tamam",
CANCEL : "İptal",
CONFIRM : "Onayla"
},
zh_CN : {
OK : "OK",
CANCEL : "取消",
CONFIRM : "确认"
},
zh_TW : {
OK : "OK",
CANCEL : "取消",
CONFIRM : "確認"
}
};
exports.addLocale = function(name, values) {
$.each(["OK", "CANCEL", "CONFIRM"], function(_, v) {
if (!values[v]) {
throw new Error("Please supply a translation for '" + v + "'");
}
});
locales[name] = {
OK: values.OK,
CANCEL: values.CANCEL,
CONFIRM: values.CONFIRM
};
return exports;
};
exports.removeLocale = function(name) {
delete locales[name];
return exports;
};
exports.setLocale = function(name) {
return exports.setDefaults("locale", name);
};
exports.init = function(_$) {
return init(_$ || $);
};
return exports;
}));/*!
* Modernizr v2.7.1
* www.modernizr.com
*
* Copyright (c) Faruk Ates, Paul Irish, Alex Sexton
* Available under the BSD and MIT licenses: www.modernizr.com/license/
*/
/*
* Modernizr tests which native CSS3 and HTML5 features are available in
* the current UA and makes the results available to you in two ways:
* as properties on a global Modernizr object, and as classes on the
* element. This information allows you to progressively enhance
* your pages with a granular level of control over the experience.
*
* Modernizr has an optional (not included) conditional resource loader
* called Modernizr.load(), based on Yepnope.js (yepnopejs.com).
* To get a build that includes Modernizr.load(), as well as choosing
* which tests to include, go to www.modernizr.com/download/
*
* Authors Faruk Ates, Paul Irish, Alex Sexton
* Contributors Ryan Seddon, Ben Alman
*/
window.Modernizr = (function( window, document, undefined ) {
var version = '2.7.1',
Modernizr = {},
/*>>cssclasses*/
enableClasses = true,
/*>>cssclasses*/
docElement = document.documentElement,
/**
* Create our "modernizr" element that we do most feature tests on.
*/
mod = 'modernizr',
modElem = document.createElement(mod),
mStyle = modElem.style,
/**
* Create the input element for various Web Forms feature tests.
*/
inputElem /*>>inputelem*/ = document.createElement('input') /*>>inputelem*/ ,
/*>>smile*/
smile = ':)',
/*>>smile*/
toString = {}.toString,
/*>>prefixes*/
prefixes = ' -webkit- -moz- -o- -ms- '.split(' '),
/*>>prefixes*/
/*>>domprefixes*/
omPrefixes = 'Webkit Moz O ms',
cssomPrefixes = omPrefixes.split(' '),
domPrefixes = omPrefixes.toLowerCase().split(' '),
/*>>domprefixes*/
/*>>ns*/
ns = {'svg': 'http://www.w3.org/2000/svg'},
/*>>ns*/
tests = {},
inputs = {},
attrs = {},
classes = [],
slice = classes.slice,
featureName, // used in testing loop
/*>>teststyles*/
injectElementWithStyles = function( rule, callback, nodes, testnames ) {
var style, ret, node, docOverflow,
div = document.createElement('div'),
body = document.body,
fakeBody = body || document.createElement('body');
if ( parseInt(nodes, 10) ) {
while ( nodes-- ) {
node = document.createElement('div');
node.id = testnames ? testnames[nodes] : mod + (nodes + 1);
div.appendChild(node);
}
}
style = ['',''].join('');
div.id = mod;
(body ? div : fakeBody).innerHTML += style;
fakeBody.appendChild(div);
if ( !body ) {
fakeBody.style.background = '';
fakeBody.style.overflow = 'hidden';
docOverflow = docElement.style.overflow;
docElement.style.overflow = 'hidden';
docElement.appendChild(fakeBody);
}
ret = callback(div, rule);
if ( !body ) {
fakeBody.parentNode.removeChild(fakeBody);
docElement.style.overflow = docOverflow;
} else {
div.parentNode.removeChild(div);
}
return !!ret;
},
/*>>teststyles*/
/*>>mq*/
testMediaQuery = function( mq ) {
var matchMedia = window.matchMedia || window.msMatchMedia;
if ( matchMedia ) {
return matchMedia(mq).matches;
}
var bool;
injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', function( node ) {
bool = (window.getComputedStyle ?
getComputedStyle(node, null) :
node.currentStyle)['position'] == 'absolute';
});
return bool;
},
/*>>mq*/
/*>>hasevent*/
isEventSupported = (function() {
var TAGNAMES = {
'select': 'input', 'change': 'input',
'submit': 'form', 'reset': 'form',
'error': 'img', 'load': 'img', 'abort': 'img'
};
function isEventSupported( eventName, element ) {
element = element || document.createElement(TAGNAMES[eventName] || 'div');
eventName = 'on' + eventName;
var isSupported = eventName in element;
if ( !isSupported ) {
if ( !element.setAttribute ) {
element = document.createElement('div');
}
if ( element.setAttribute && element.removeAttribute ) {
element.setAttribute(eventName, '');
isSupported = is(element[eventName], 'function');
if ( !is(element[eventName], 'undefined') ) {
element[eventName] = undefined;
}
element.removeAttribute(eventName);
}
}
element = null;
return isSupported;
}
return isEventSupported;
})(),
/*>>hasevent*/
_hasOwnProperty = ({}).hasOwnProperty, hasOwnProp;
if ( !is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined') ) {
hasOwnProp = function (object, property) {
return _hasOwnProperty.call(object, property);
};
}
else {
hasOwnProp = function (object, property) { /* yes, this can give false positives/negatives, but most of the time we don't care about those */
return ((property in object) && is(object.constructor.prototype[property], 'undefined'));
};
}
if (!Function.prototype.bind) {
Function.prototype.bind = function bind(that) {
var target = this;
if (typeof target != "function") {
throw new TypeError();
}
var args = slice.call(arguments, 1),
bound = function () {
if (this instanceof bound) {
var F = function(){};
F.prototype = target.prototype;
var self = new F();
var result = target.apply(
self,
args.concat(slice.call(arguments))
);
if (Object(result) === result) {
return result;
}
return self;
} else {
return target.apply(
that,
args.concat(slice.call(arguments))
);
}
};
return bound;
};
}
/**
* setCss applies given styles to the Modernizr DOM node.
*/
function setCss( str ) {
mStyle.cssText = str;
}
/**
* setCssAll extrapolates all vendor-specific css strings.
*/
function setCssAll( str1, str2 ) {
return setCss(prefixes.join(str1 + ';') + ( str2 || '' ));
}
/**
* is returns a boolean for if typeof obj is exactly type.
*/
function is( obj, type ) {
return typeof obj === type;
}
/**
* contains returns a boolean for if substr is found within str.
*/
function contains( str, substr ) {
return !!~('' + str).indexOf(substr);
}
/*>>testprop*/
function testProps( props, prefixed ) {
for ( var i in props ) {
var prop = props[i];
if ( !contains(prop, "-") && mStyle[prop] !== undefined ) {
return prefixed == 'pfx' ? prop : true;
}
}
return false;
}
/*>>testprop*/
/**
* testDOMProps is a generic DOM property test; if a browser supports
* a certain property, it won't return undefined for it.
*/
function testDOMProps( props, obj, elem ) {
for ( var i in props ) {
var item = obj[props[i]];
if ( item !== undefined) {
if (elem === false) return props[i];
if (is(item, 'function')){
return item.bind(elem || obj);
}
return item;
}
}
return false;
}
/*>>testallprops*/
/**
* testPropsAll tests a list of DOM properties we want to check against.
* We specify literally ALL possible (known and/or likely) properties on
* the element including the non-vendor prefixed one, for forward-
* compatibility.
*/
function testPropsAll( prop, prefixed, elem ) {
var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1),
props = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' ');
if(is(prefixed, "string") || is(prefixed, "undefined")) {
return testProps(props, prefixed);
} else {
props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' ');
return testDOMProps(props, prefixed, elem);
}
}
/*>>testallprops*/
/**
* Tests
* -----
*/
tests['flexbox'] = function() {
return testPropsAll('flexWrap');
};
tests['flexboxlegacy'] = function() {
return testPropsAll('boxDirection');
};
tests['canvas'] = function() {
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
};
tests['canvastext'] = function() {
return !!(Modernizr['canvas'] && is(document.createElement('canvas').getContext('2d').fillText, 'function'));
};
tests['webgl'] = function() {
return !!window.WebGLRenderingContext;
};
/*
* The Modernizr.touch test only indicates if the browser supports
* touch events, which does not necessarily reflect a touchscreen
* device, as evidenced by tablets running Windows 7 or, alas,
* the Palm Pre / WebOS (touch) phones.
*
* Additionally, Chrome (desktop) used to lie about its support on this,
* but that has since been rectified: crbug.com/36415
*
* We also test for Firefox 4 Multitouch Support.
*
* For more info, see: modernizr.github.com/Modernizr/touch.html
*/
tests['touch'] = function() {
var bool;
if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
bool = true;
} else {
injectElementWithStyles(['@media (',prefixes.join('touch-enabled),('),mod,')','{#modernizr{top:9px;position:absolute}}'].join(''), function( node ) {
bool = node.offsetTop === 9;
});
}
return bool;
};
tests['geolocation'] = function() {
return 'geolocation' in navigator;
};
tests['postmessage'] = function() {
return !!window.postMessage;
};
tests['websqldatabase'] = function() {
return !!window.openDatabase;
};
tests['indexedDB'] = function() {
return !!testPropsAll("indexedDB", window);
};
tests['hashchange'] = function() {
return isEventSupported('hashchange', window) && (document.documentMode === undefined || document.documentMode > 7);
};
tests['history'] = function() {
return !!(window.history && history.pushState);
};
tests['draganddrop'] = function() {
var div = document.createElement('div');
return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div);
};
tests['websockets'] = function() {
return 'WebSocket' in window || 'MozWebSocket' in window;
};
tests['rgba'] = function() {
setCss('background-color:rgba(150,255,150,.5)');
return contains(mStyle.backgroundColor, 'rgba');
};
tests['hsla'] = function() {
setCss('background-color:hsla(120,40%,100%,.5)');
return contains(mStyle.backgroundColor, 'rgba') || contains(mStyle.backgroundColor, 'hsla');
};
tests['multiplebgs'] = function() {
setCss('background:url(https://),url(https://),red url(https://)');
return (/(url\s*\(.*?){3}/).test(mStyle.background);
};
tests['backgroundsize'] = function() {
return testPropsAll('backgroundSize');
};
tests['borderimage'] = function() {
return testPropsAll('borderImage');
};
tests['borderradius'] = function() {
return testPropsAll('borderRadius');
};
tests['boxshadow'] = function() {
return testPropsAll('boxShadow');
};
tests['textshadow'] = function() {
return document.createElement('div').style.textShadow === '';
};
tests['opacity'] = function() {
setCssAll('opacity:.55');
return (/^0.55$/).test(mStyle.opacity);
};
tests['cssanimations'] = function() {
return testPropsAll('animationName');
};
tests['csscolumns'] = function() {
return testPropsAll('columnCount');
};
tests['cssgradients'] = function() {
/**
* For CSS Gradients syntax, please see:
* webkit.org/blog/175/introducing-css-gradients/
* developer.mozilla.org/en/CSS/-moz-linear-gradient
* developer.mozilla.org/en/CSS/-moz-radial-gradient
* dev.w3.org/csswg/css3-images/#gradients-
*/
var str1 = 'background-image:',
str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));',
str3 = 'linear-gradient(left top,#9f9, white);';
setCss(
(str1 + '-webkit- '.split(' ').join(str2 + str1) +
prefixes.join(str3 + str1)).slice(0, -str1.length)
);
return contains(mStyle.backgroundImage, 'gradient');
};
tests['cssreflections'] = function() {
return testPropsAll('boxReflect');
};
tests['csstransforms'] = function() {
return !!testPropsAll('transform');
};
tests['csstransforms3d'] = function() {
var ret = !!testPropsAll('perspective');
if ( ret && 'webkitPerspective' in docElement.style ) {
injectElementWithStyles('@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}', function( node, rule ) {
ret = node.offsetLeft === 9 && node.offsetHeight === 3;
});
}
return ret;
};
tests['csstransitions'] = function() {
return testPropsAll('transition');
};
/*>>fontface*/
tests['fontface'] = function() {
var bool;
injectElementWithStyles('@font-face {font-family:"font";src:url("https://")}', function( node, rule ) {
var style = document.getElementById('smodernizr'),
sheet = style.sheet || style.styleSheet,
cssText = sheet ? (sheet.cssRules && sheet.cssRules[0] ? sheet.cssRules[0].cssText : sheet.cssText || '') : '';
bool = /src/i.test(cssText) && cssText.indexOf(rule.split(' ')[0]) === 0;
});
return bool;
};
/*>>fontface*/
tests['generatedcontent'] = function() {
var bool;
injectElementWithStyles(['#',mod,'{font:0/0 a}#',mod,':after{content:"',smile,'";visibility:hidden;font:3px/1 a}'].join(''), function( node ) {
bool = node.offsetHeight >= 3;
});
return bool;
};
tests['video'] = function() {
var elem = document.createElement('video'),
bool = false;
try {
if ( bool = !!elem.canPlayType ) {
bool = new Boolean(bool);
bool.ogg = elem.canPlayType('video/ogg; codecs="theora"') .replace(/^no$/,'');
bool.h264 = elem.canPlayType('video/mp4; codecs="avc1.42E01E"') .replace(/^no$/,'');
bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,'');
}
} catch(e) { }
return bool;
};
tests['audio'] = function() {
var elem = document.createElement('audio'),
bool = false;
try {
if ( bool = !!elem.canPlayType ) {
bool = new Boolean(bool);
bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,'');
bool.mp3 = elem.canPlayType('audio/mpeg;') .replace(/^no$/,'');
bool.wav = elem.canPlayType('audio/wav; codecs="1"') .replace(/^no$/,'');
bool.m4a = ( elem.canPlayType('audio/x-m4a;') ||
elem.canPlayType('audio/aac;')) .replace(/^no$/,'');
}
} catch(e) { }
return bool;
};
tests['localstorage'] = function() {
try {
localStorage.setItem(mod, mod);
localStorage.removeItem(mod);
return true;
} catch(e) {
return false;
}
};
tests['sessionstorage'] = function() {
try {
sessionStorage.setItem(mod, mod);
sessionStorage.removeItem(mod);
return true;
} catch(e) {
return false;
}
};
tests['webworkers'] = function() {
return !!window.Worker;
};
tests['applicationcache'] = function() {
return !!window.applicationCache;
};
tests['svg'] = function() {
return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect;
};
tests['inlinesvg'] = function() {
var div = document.createElement('div');
div.innerHTML = '';
return (div.firstChild && div.firstChild.namespaceURI) == ns.svg;
};
tests['smil'] = function() {
return !!document.createElementNS && /SVGAnimate/.test(toString.call(document.createElementNS(ns.svg, 'animate')));
};
tests['svgclippaths'] = function() {
return !!document.createElementNS && /SVGClipPath/.test(toString.call(document.createElementNS(ns.svg, 'clipPath')));
};
/*>>webforms*/
function webforms() {
/*>>input*/
Modernizr['input'] = (function( props ) {
for ( var i = 0, len = props.length; i < len; i++ ) {
attrs[ props[i] ] = !!(props[i] in inputElem);
}
if (attrs.list){
attrs.list = !!(document.createElement('datalist') && window.HTMLDataListElement);
}
return attrs;
})('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' '));
/*>>input*/
/*>>inputtypes*/
Modernizr['inputtypes'] = (function(props) {
for ( var i = 0, bool, inputElemType, defaultView, len = props.length; i < len; i++ ) {
inputElem.setAttribute('type', inputElemType = props[i]);
bool = inputElem.type !== 'text';
if ( bool ) {
inputElem.value = smile;
inputElem.style.cssText = 'position:absolute;visibility:hidden;';
if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) {
docElement.appendChild(inputElem);
defaultView = document.defaultView;
bool = defaultView.getComputedStyle &&
defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' &&
(inputElem.offsetHeight !== 0);
docElement.removeChild(inputElem);
} else if ( /^(search|tel)$/.test(inputElemType) ){
} else if ( /^(url|email)$/.test(inputElemType) ) {
bool = inputElem.checkValidity && inputElem.checkValidity() === false;
} else {
bool = inputElem.value != smile;
}
}
inputs[ props[i] ] = !!bool;
}
return inputs;
})('search tel url email datetime date month week time datetime-local number range color'.split(' '));
/*>>inputtypes*/
}
/*>>webforms*/
for ( var feature in tests ) {
if ( hasOwnProp(tests, feature) ) {
featureName = feature.toLowerCase();
Modernizr[featureName] = tests[feature]();
classes.push((Modernizr[featureName] ? '' : 'no-') + featureName);
}
}
/*>>webforms*/
Modernizr.input || webforms();
/*>>webforms*/
/**
* addTest allows the user to define their own feature tests
* the result will be added onto the Modernizr object,
* as well as an appropriate className set on the html element
*
* @param feature - String naming the feature
* @param test - Function returning true if feature is supported, false if not
*/
Modernizr.addTest = function ( feature, test ) {
if ( typeof feature == 'object' ) {
for ( var key in feature ) {
if ( hasOwnProp( feature, key ) ) {
Modernizr.addTest( key, feature[ key ] );
}
}
} else {
feature = feature.toLowerCase();
if ( Modernizr[feature] !== undefined ) {
return Modernizr;
}
test = typeof test == 'function' ? test() : test;
if (typeof enableClasses !== "undefined" && enableClasses) {
docElement.className += ' ' + (test ? '' : 'no-') + feature;
}
Modernizr[feature] = test;
}
return Modernizr; // allow chaining.
};
setCss('');
modElem = inputElem = null;
/*>>shiv*/
/**
* @preserve HTML5 Shiv prev3.7.1 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
*/
;(function(window, document) {
/*jshint evil:true */
/** version */
var version = '3.7.0';
/** Preset options */
var options = window.html5 || {};
/** Used to skip problem elements */
var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i;
/** Not all elements can be cloned in IE **/
var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i;
/** Detect whether the browser supports default html5 styles */
var supportsHtml5Styles;
/** Name of the expando, to work with multiple documents or to re-shiv one document */
var expando = '_html5shiv';
/** The id for the the documents expando */
var expanID = 0;
/** Cached data for each document */
var expandoData = {};
/** Detect whether the browser supports unknown elements */
var supportsUnknownElements;
(function() {
try {
var a = document.createElement('a');
a.innerHTML = '';
supportsHtml5Styles = ('hidden' in a);
supportsUnknownElements = a.childNodes.length == 1 || (function() {
(document.createElement)('a');
var frag = document.createDocumentFragment();
return (
typeof frag.cloneNode == 'undefined' ||
typeof frag.createDocumentFragment == 'undefined' ||
typeof frag.createElement == 'undefined'
);
}());
} catch(e) {
supportsHtml5Styles = true;
supportsUnknownElements = true;
}
}());
/*--------------------------------------------------------------------------*/
/**
* Creates a style sheet with the given CSS text and adds it to the document.
* @private
* @param {Document} ownerDocument The document.
* @param {String} cssText The CSS text.
* @returns {StyleSheet} The style element.
*/
function addStyleSheet(ownerDocument, cssText) {
var p = ownerDocument.createElement('p'),
parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement;
p.innerHTML = 'x';
return parent.insertBefore(p.lastChild, parent.firstChild);
}
/**
* Returns the value of `html5.elements` as an array.
* @private
* @returns {Array} An array of shived element node names.
*/
function getElements() {
var elements = html5.elements;
return typeof elements == 'string' ? elements.split(' ') : elements;
}
/**
* Returns the data associated to the given document
* @private
* @param {Document} ownerDocument The document.
* @returns {Object} An object of data.
*/
function getExpandoData(ownerDocument) {
var data = expandoData[ownerDocument[expando]];
if (!data) {
data = {};
expanID++;
ownerDocument[expando] = expanID;
expandoData[expanID] = data;
}
return data;
}
/**
* returns a shived element for the given nodeName and document
* @memberOf html5
* @param {String} nodeName name of the element
* @param {Document} ownerDocument The context document.
* @returns {Object} The shived element.
*/
function createElement(nodeName, ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createElement(nodeName);
}
if (!data) {
data = getExpandoData(ownerDocument);
}
var node;
if (data.cache[nodeName]) {
node = data.cache[nodeName].cloneNode();
} else if (saveClones.test(nodeName)) {
node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode();
} else {
node = data.createElem(nodeName);
}
return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node;
}
/**
* returns a shived DocumentFragment for the given document
* @memberOf html5
* @param {Document} ownerDocument The context document.
* @returns {Object} The shived DocumentFragment.
*/
function createDocumentFragment(ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createDocumentFragment();
}
data = data || getExpandoData(ownerDocument);
var clone = data.frag.cloneNode(),
i = 0,
elems = getElements(),
l = elems.length;
for(;i>shiv*/
Modernizr._version = version;
/*>>prefixes*/
Modernizr._prefixes = prefixes;
/*>>prefixes*/
/*>>domprefixes*/
Modernizr._domPrefixes = domPrefixes;
Modernizr._cssomPrefixes = cssomPrefixes;
/*>>domprefixes*/
/*>>mq*/
Modernizr.mq = testMediaQuery;
/*>>mq*/
/*>>hasevent*/
Modernizr.hasEvent = isEventSupported;
/*>>hasevent*/
/*>>testprop*/
Modernizr.testProp = function(prop){
return testProps([prop]);
};
/*>>testprop*/
/*>>testallprops*/
Modernizr.testAllProps = testPropsAll;
/*>>testallprops*/
/*>>teststyles*/
Modernizr.testStyles = injectElementWithStyles;
/*>>teststyles*/
/*>>prefixed*/
Modernizr.prefixed = function(prop, obj, elem){
if(!obj) {
return testPropsAll(prop, 'pfx');
} else {
return testPropsAll(prop, obj, elem);
}
};
/*>>prefixed*/
/*>>cssclasses*/
docElement.className = docElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') +
(enableClasses ? ' js ' + classes.join(' ') : '');
/*>>cssclasses*/
return Modernizr;
})(this, this.document);/*!
* Isotope PACKAGED v3.0.1
*
* Licensed GPLv3 for open source use
* or Isotope Commercial License for commercial use
*
* http://isotope.metafizzy.co
* Copyright 2016 Metafizzy
*/
!function(t,e){"use strict";"function"==typeof define&&define.amd?define("jquery-bridget/jquery-bridget",["jquery"],function(i){e(t,i)}):"object"==typeof module&&module.exports?module.exports=e(t,require("jquery")):t.jQueryBridget=e(t,t.jQuery)}(window,function(t,e){"use strict";function i(i,s,a){function u(t,e,n){var o,s="$()."+i+'("'+e+'")';return t.each(function(t,u){var h=a.data(u,i);if(!h)return void r(i+" not initialized. Cannot call methods, i.e. "+s);var d=h[e];if(!d||"_"==e.charAt(0))return void r(s+" is not a valid method");var l=d.apply(h,n);o=void 0===o?l:o}),void 0!==o?o:t}function h(t,e){t.each(function(t,n){var o=a.data(n,i);o?(o.option(e),o._init()):(o=new s(n,e),a.data(n,i,o))})}a=a||e||t.jQuery,a&&(s.prototype.option||(s.prototype.option=function(t){a.isPlainObject(t)&&(this.options=a.extend(!0,this.options,t))}),a.fn[i]=function(t){if("string"==typeof t){var e=o.call(arguments,1);return u(this,t,e)}return h(this,t),this},n(a))}function n(t){!t||t&&t.bridget||(t.bridget=i)}var o=Array.prototype.slice,s=t.console,r="undefined"==typeof s?function(){}:function(t){s.error(t)};return n(e||t.jQuery),i}),function(t,e){"function"==typeof define&&define.amd?define("ev-emitter/ev-emitter",e):"object"==typeof module&&module.exports?module.exports=e():t.EvEmitter=e()}("undefined"!=typeof window?window:this,function(){function t(){}var e=t.prototype;return e.on=function(t,e){if(t&&e){var i=this._events=this._events||{},n=i[t]=i[t]||[];return-1==n.indexOf(e)&&n.push(e),this}},e.once=function(t,e){if(t&&e){this.on(t,e);var i=this._onceEvents=this._onceEvents||{},n=i[t]=i[t]||{};return n[e]=!0,this}},e.off=function(t,e){var i=this._events&&this._events[t];if(i&&i.length){var n=i.indexOf(e);return-1!=n&&i.splice(n,1),this}},e.emitEvent=function(t,e){var i=this._events&&this._events[t];if(i&&i.length){var n=0,o=i[n];e=e||[];for(var s=this._onceEvents&&this._onceEvents[t];o;){var r=s&&s[o];r&&(this.off(t,o),delete s[o]),o.apply(this,e),n+=r?0:1,o=i[n]}return this}},t}),function(t,e){"use strict";"function"==typeof define&&define.amd?define("get-size/get-size",[],function(){return e()}):"object"==typeof module&&module.exports?module.exports=e():t.getSize=e()}(window,function(){"use strict";function t(t){var e=parseFloat(t),i=-1==t.indexOf("%")&&!isNaN(e);return i&&e}function e(){}function i(){for(var t={width:0,height:0,innerWidth:0,innerHeight:0,outerWidth:0,outerHeight:0},e=0;h>e;e++){var i=u[e];t[i]=0}return t}function n(t){var e=getComputedStyle(t);return e||a("Style returned "+e+". Are you running this code in a hidden iframe on Firefox? See http://bit.ly/getsizebug1"),e}function o(){if(!d){d=!0;var e=document.createElement("div");e.style.width="200px",e.style.padding="1px 2px 3px 4px",e.style.borderStyle="solid",e.style.borderWidth="1px 2px 3px 4px",e.style.boxSizing="border-box";var i=document.body||document.documentElement;i.appendChild(e);var o=n(e);s.isBoxSizeOuter=r=200==t(o.width),i.removeChild(e)}}function s(e){if(o(),"string"==typeof e&&(e=document.querySelector(e)),e&&"object"==typeof e&&e.nodeType){var s=n(e);if("none"==s.display)return i();var a={};a.width=e.offsetWidth,a.height=e.offsetHeight;for(var d=a.isBorderBox="border-box"==s.boxSizing,l=0;h>l;l++){var f=u[l],c=s[f],m=parseFloat(c);a[f]=isNaN(m)?0:m}var p=a.paddingLeft+a.paddingRight,y=a.paddingTop+a.paddingBottom,g=a.marginLeft+a.marginRight,v=a.marginTop+a.marginBottom,_=a.borderLeftWidth+a.borderRightWidth,I=a.borderTopWidth+a.borderBottomWidth,z=d&&r,x=t(s.width);x!==!1&&(a.width=x+(z?0:p+_));var S=t(s.height);return S!==!1&&(a.height=S+(z?0:y+I)),a.innerWidth=a.width-(p+_),a.innerHeight=a.height-(y+I),a.outerWidth=a.width+g,a.outerHeight=a.height+v,a}}var r,a="undefined"==typeof console?e:function(t){console.error(t)},u=["paddingLeft","paddingRight","paddingTop","paddingBottom","marginLeft","marginRight","marginTop","marginBottom","borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth"],h=u.length,d=!1;return s}),function(t,e){"use strict";"function"==typeof define&&define.amd?define("desandro-matches-selector/matches-selector",e):"object"==typeof module&&module.exports?module.exports=e():t.matchesSelector=e()}(window,function(){"use strict";var t=function(){var t=Element.prototype;if(t.matches)return"matches";if(t.matchesSelector)return"matchesSelector";for(var e=["webkit","moz","ms","o"],i=0;ir?"round":"floor";s=Math[a](s),this.cols=Math.max(s,1)},i.prototype.getContainerWidth=function(){var t=this._getOption("fitWidth"),i=t?this.element.parentNode:this.element,n=e(i);this.containerWidth=n&&n.innerWidth},i.prototype._getItemLayoutPosition=function(t){t.getSize();var e=t.size.outerWidth%this.columnWidth,i=e&&1>e?"round":"ceil",n=Math[i](t.size.outerWidth/this.columnWidth);n=Math.min(n,this.cols);for(var o=this._getColGroup(n),s=Math.min.apply(Math,o),r=o.indexOf(s),a={x:this.columnWidth*r,y:s},u=s+t.size.outerHeight,h=this.cols+1-o.length,d=0;h>d;d++)this.colYs[r+d]=u;return a},i.prototype._getColGroup=function(t){if(2>t)return this.colYs;for(var e=[],i=this.cols+1-t,n=0;i>n;n++){var o=this.colYs.slice(n,n+t);e[n]=Math.max.apply(Math,o)}return e},i.prototype._manageStamp=function(t){var i=e(t),n=this._getElementOffset(t),o=this._getOption("originLeft"),s=o?n.left:n.right,r=s+i.outerWidth,a=Math.floor(s/this.columnWidth);a=Math.max(0,a);var u=Math.floor(r/this.columnWidth);u-=r%this.columnWidth?0:1,u=Math.min(this.cols-1,u);for(var h=this._getOption("originTop"),d=(h?n.top:n.bottom)+i.outerHeight,l=a;u>=l;l++)this.colYs[l]=Math.max(d,this.colYs[l])},i.prototype._getContainerSize=function(){this.maxY=Math.max.apply(Math,this.colYs);var t={height:this.maxY};return this._getOption("fitWidth")&&(t.width=this._getContainerFitWidth()),t},i.prototype._getContainerFitWidth=function(){for(var t=0,e=this.cols;--e&&0===this.colYs[e];)t++;return(this.cols-t)*this.columnWidth-this.gutter},i.prototype.needsResizeLayout=function(){var t=this.containerWidth;return this.getContainerWidth(),t!=this.containerWidth},i}),function(t,e){"function"==typeof define&&define.amd?define("isotope/js/layout-modes/masonry",["../layout-mode","masonry/masonry"],e):"object"==typeof module&&module.exports?module.exports=e(require("../layout-mode"),require("masonry-layout")):e(t.Isotope.LayoutMode,t.Masonry)}(window,function(t,e){"use strict";var i=t.create("masonry"),n=i.prototype,o={_getElementOffset:!0,layout:!0,_getMeasurement:!0};for(var s in e.prototype)o[s]||(n[s]=e.prototype[s]);var r=n.measureColumns;n.measureColumns=function(){this.items=this.isotope.filteredItems,r.call(this)};var a=n._getOption;return n._getOption=function(t){return"fitWidth"==t?void 0!==this.options.isFitWidth?this.options.isFitWidth:this.options.fitWidth:a.apply(this.isotope,arguments)},i}),function(t,e){"function"==typeof define&&define.amd?define("isotope/js/layout-modes/fit-rows",["../layout-mode"],e):"object"==typeof exports?module.exports=e(require("../layout-mode")):e(t.Isotope.LayoutMode)}(window,function(t){"use strict";var e=t.create("fitRows"),i=e.prototype;return i._resetLayout=function(){this.x=0,this.y=0,this.maxY=0,this._getMeasurement("gutter","outerWidth")},i._getItemLayoutPosition=function(t){t.getSize();var e=t.size.outerWidth+this.gutter,i=this.isotope.size.innerWidth+this.gutter;0!==this.x&&e+this.x>i&&(this.x=0,this.y=this.maxY);var n={x:this.x,y:this.y};return this.maxY=Math.max(this.maxY,this.y+t.size.outerHeight),this.x+=e,n},i._getContainerSize=function(){return{height:this.maxY}},e}),function(t,e){"function"==typeof define&&define.amd?define("isotope/js/layout-modes/vertical",["../layout-mode"],e):"object"==typeof module&&module.exports?module.exports=e(require("../layout-mode")):e(t.Isotope.LayoutMode)}(window,function(t){"use strict";var e=t.create("vertical",{horizontalAlignment:0}),i=e.prototype;return i._resetLayout=function(){this.y=0},i._getItemLayoutPosition=function(t){t.getSize();var e=(this.isotope.size.innerWidth-t.size.outerWidth)*this.options.horizontalAlignment,i=this.y;return this.y+=t.size.outerHeight,{x:e,y:i}},i._getContainerSize=function(){return{height:this.y}},e}),function(t,e){"function"==typeof define&&define.amd?define(["outlayer/outlayer","get-size/get-size","desandro-matches-selector/matches-selector","fizzy-ui-utils/utils","isotope/js/item","isotope/js/layout-mode","isotope/js/layout-modes/masonry","isotope/js/layout-modes/fit-rows","isotope/js/layout-modes/vertical"],function(i,n,o,s,r,a){return e(t,i,n,o,s,r,a)}):"object"==typeof module&&module.exports?module.exports=e(t,require("outlayer"),require("get-size"),require("desandro-matches-selector"),require("fizzy-ui-utils"),require("isotope/js/item"),require("isotope/js/layout-mode"),require("isotope/js/layout-modes/masonry"),require("isotope/js/layout-modes/fit-rows"),require("isotope/js/layout-modes/vertical")):t.Isotope=e(t,t.Outlayer,t.getSize,t.matchesSelector,t.fizzyUIUtils,t.Isotope.Item,t.Isotope.LayoutMode)}(window,function(t,e,i,n,o,s,r){function a(t,e){return function(i,n){for(var o=0;oa||a>r){var u=void 0!==e[s]?e[s]:e,h=u?1:-1;return(r>a?1:-1)*h}}return 0}}var u=t.jQuery,h=String.prototype.trim?function(t){return t.trim()}:function(t){return t.replace(/^\s+|\s+$/g,"")},d=e.create("isotope",{layoutMode:"masonry",isJQueryFiltering:!0,sortAscending:!0});d.Item=s,d.LayoutMode=r;var l=d.prototype;l._create=function(){this.itemGUID=0,this._sorters={},this._getSorters(),e.prototype._create.call(this),this.modes={},this.filteredItems=this.items,this.sortHistory=["original-order"];for(var t in r.modes)this._initLayoutMode(t)},l.reloadItems=function(){this.itemGUID=0,e.prototype.reloadItems.call(this)},l._itemize=function(){for(var t=e.prototype._itemize.apply(this,arguments),i=0;ii;i++){var n=t[i];n.updateSortData()}};var f=function(){function t(t){if("string"!=typeof t)return t;var i=h(t).split(" "),n=i[0],o=n.match(/^\[(.+)\]$/),s=o&&o[1],r=e(s,n),a=d.sortDataParsers[i[1]];
return t=a?function(t){return t&&a(r(t))}:function(t){return t&&r(t)}}function e(t,e){return t?function(e){return e.getAttribute(t)}:function(t){var i=t.querySelector(e);return i&&i.textContent}}return t}();d.sortDataParsers={parseInt:function(t){return parseInt(t,10)},parseFloat:function(t){return parseFloat(t)}},l._sort=function(){var t=this.options.sortBy;if(t){var e=[].concat.apply(t,this.sortHistory),i=a(e,this.options.sortAscending);this.filteredItems.sort(i),t!=this.sortHistory[0]&&this.sortHistory.unshift(t)}},l._mode=function(){var t=this.options.layoutMode,e=this.modes[t];if(!e)throw new Error("No layout mode: "+t);return e.options=this.options[t],e},l._resetLayout=function(){e.prototype._resetLayout.call(this),this._mode()._resetLayout()},l._getItemLayoutPosition=function(t){return this._mode()._getItemLayoutPosition(t)},l._manageStamp=function(t){this._mode()._manageStamp(t)},l._getContainerSize=function(){return this._mode()._getContainerSize()},l.needsResizeLayout=function(){return this._mode().needsResizeLayout()},l.appended=function(t){var e=this.addItems(t);if(e.length){var i=this._filterRevealAdded(e);this.filteredItems=this.filteredItems.concat(i)}},l.prepended=function(t){var e=this._itemize(t);if(e.length){this._resetLayout(),this._manageStamps();var i=this._filterRevealAdded(e);this.layoutItems(this.filteredItems),this.filteredItems=i.concat(this.filteredItems),this.items=e.concat(this.items)}},l._filterRevealAdded=function(t){var e=this._filter(t);return this.hide(e.needHide),this.reveal(e.matches),this.layoutItems(e.matches,!0),e.matches},l.insert=function(t){var e=this.addItems(t);if(e.length){var i,n,o=e.length;for(i=0;o>i;i++)n=e[i],this.element.appendChild(n.element);var s=this._filter(e).matches;for(i=0;o>i;i++)e[i].isLayoutInstant=!0;for(this.arrange(),i=0;o>i;i++)delete e[i].isLayoutInstant;this.reveal(s)}};var c=l.remove;return l.remove=function(t){t=o.makeArray(t);var e=this.getItems(t);c.call(this,t);for(var i=e&&e.length,n=0;i&&i>n;n++){var s=e[n];o.removeFrom(this.filteredItems,s)}},l.shuffle=function(){for(var t=0;t 4) {
this.options = $.extend(true, {}, this.options, {
responsive: {
1199: {
items: this.options.items
}
}
});
}
if (this.options.autoHeight) {
$(window).afterResize(function() {
$el.find('.owl-stage-outer').height( $el.find('.owl-item.active').height() );
});
$(window).load(function() {
$el.find('.owl-stage-outer').height( $el.find('.owl-item.active').height() );
});
}
$el.owlCarousel(this.options).addClass("owl-carousel-init");
return this;
}
};
$.extend(theme, {
PluginCarousel: PluginCarousel
});
$.fn.themePluginCarousel = function(opts) {
return this.map(function() {
var $this = $(this);
if ($this.data(instanceName)) {
return $this.data(instanceName);
} else {
return new PluginCarousel($this, opts);
}
});
}
}).apply(this, [window.theme, jQuery]);
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginCarousel'])) {
$(function() {
$('[data-plugin-carousel]:not(.manual), .owl-carousel:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginCarousel(opts);
});
});
}
}).apply(this, [jQuery]);/**
* Plugin Name: Count To
* Written by: Matt Huggins - https://github.com/mhuggins/jquery-countTo
*/
(function ($) {
$.fn.countTo = function (options) {
options = options || {};
return $(this).each(function () {
var settings = $.extend({}, $.fn.countTo.defaults, {
from: $(this).data('from'),
to: $(this).data('to'),
speed: $(this).data('speed'),
refreshInterval: $(this).data('refresh-interval'),
decimals: $(this).data('decimals')
}, options);
var loops = Math.ceil(settings.speed / settings.refreshInterval),
increment = (settings.to - settings.from) / loops;
var self = this,
$self = $(this),
loopCount = 0,
value = settings.from,
data = $self.data('countTo') || {};
$self.data('countTo', data);
if (data.interval) {
clearInterval(data.interval);
}
data.interval = setInterval(updateTimer, settings.refreshInterval);
render(value);
function updateTimer() {
value += increment;
loopCount++;
render(value);
if (typeof(settings.onUpdate) == 'function') {
settings.onUpdate.call(self, value);
}
if (loopCount >= loops) {
$self.removeData('countTo');
clearInterval(data.interval);
value = settings.to;
if (typeof(settings.onComplete) == 'function') {
settings.onComplete.call(self, value);
}
}
}
function render(value) {
var formattedValue = settings.formatter.call(self, value, settings);
$self.html(formattedValue);
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 0, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
formatter: formatter, // handler for formatting the value before rendering
onUpdate: null, // callback method for every time the element is updated
onComplete: null // callback method for when the element finishes updating
};
function formatter(value, settings) {
return value.toFixed(settings.decimals);
}
}(jQuery));
/**
* Counter Module.
* Dependencies - jQuery Count To Plugin - https://github.com/mhuggins/jquery-countTo
*/
(function(theme, $) {
theme = theme || {};
var instanceName = '__counter';
var PluginCounter = function($el, opts) {
return this.initialize($el, opts);
};
PluginCounter.defaults = {
accX: 0,
accY: 0,
speed: 3000,
refreshInterval: 100,
decimals: 0,
onUpdate: null,
onComplete: null
};
PluginCounter.prototype = {
initialize: function($el, opts) {
if ($el.data(instanceName)) {
return this;
}
this.$el = $el;
this
.setData()
.setOptions(opts)
.build();
return this;
},
setData: function() {
this.$el.data(instanceName, this);
return this;
},
setOptions: function(opts) {
this.options = $.extend(true, {}, PluginCounter.defaults, opts, {
wrapper: this.$el
});
return this;
},
build: function() {
if (!($.isFunction($.fn.countTo))) {
return this;
}
var self = this,
$el = this.options.wrapper;
$.extend(self.options, {
onComplete: function() {
if ($el.data('append')) {
$el.html($el.html() + $el.data('append'));
}
if ($el.data('prepend')) {
$el.html($el.data('prepend') + $el.html());
}
}
});
$el.appear(function() {
$el.countTo(self.options);
}, {
accX: self.options.accX,
accY: self.options.accY
});
return this;
}
};
$.extend(theme, {
PluginCounter: PluginCounter
});
$.fn.themePluginCounter = function(opts) {
return this.map(function() {
var $this = $(this);
if ($this.data(instanceName)) {
return $this.data(instanceName);
} else {
return new PluginCounter($this, opts);
}
});
}
}).apply(this, [window.theme, jQuery]);
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginCounter'])) {
$(function() {
$('[data-plugin-counter]:not(.manual), .counters [data-to]').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginCounter(opts);
});
});
}
}).apply(this, [jQuery]);jQuery(function($) {
$( document ).on( 's123.page.ready', function( event ) {
var layoutNUM = $('#layoutNUM').val();
if (layoutNUM!='2' && layoutNUM!='15' && layoutNUM!='3' && layoutNUM!='11' && layoutNUM!='4' && layoutNUM!='20') {
if ($('.inside_page').length==0) {
if ($('.opacity-full').length>0) { //If there is no opacity FULL we take the menu right when we start scroll
var fixedMenuAfterFirstScroll = $('#mainNav').height()+parseInt($('body').css('margin-top'),10);
} else {
if (layoutNUM!='13') {
var fixedMenuAfterFirstScroll = parseInt($('body').css('margin-top'),10);
} else {
var fixedMenuAfterFirstScroll = parseInt($('body').css('margin-top'),10)+40; //Layout 13 have 40px margin top
}
}
if (fixedMenuAfterFirstScroll==0) {
fixedMenuAfterFirstScroll = 1;
}
} else {
var fixedMenuAfterFirstScroll = parseInt($('body').css('margin-top'),10);
}
$('#mainNav').affix({
offset: {
top: fixedMenuAfterFirstScroll
}
});
if ($('.inside_page').length==0) {
var HighlightMenuOnScrollOffset = $('#mainNav').height()+parseInt($('body').css('margin-top'),10);
} else {
var HighlightMenuOnScrollOffset = parseInt($('body').css('margin-top'),10);
}
$('body').scrollspy({
target: '#mainNav',
offset: HighlightMenuOnScrollOffset
});
if (typeof document.fonts === 'undefined' || typeof document.fonts.ready === 'undefined' || typeof document.fonts.ready.then === 'undefined') {
setTimeout(function() {
ReduseMenuSizeWhenWeDontHavePlace();
},150);
} else {
document.fonts.ready.then(function () {
ReduseMenuSizeWhenWeDontHavePlace();
});
}
$( window ).resize(function() {
ReduseMenuSizeWhenWeDontHavePlace();
});
}
});
});jQuery(function($) {
$( document ).on( 's123.page.ready', function( event ) {
var layoutNUM = $('#layoutNUM').val();
if (layoutNUM=='2') {
var beforeScrollMenuHeight = $('#mainNav .navbar-header').height()+parseInt($('body').css('margin-top'),10);
$('body').scrollspy({
target: '#mainNav #top-menu',
offset: beforeScrollMenuHeight
});
$('#mainNav #top-menu').affix({
offset: {
top: beforeScrollMenuHeight
}
});
if (typeof document.fonts === 'undefined' || typeof document.fonts.ready === 'undefined' || typeof document.fonts.ready.then === 'undefined') {
setTimeout(function() {
ReduseMenuSizeWhenWeDontHavePlace();
},150);
} else {
document.fonts.ready.then(function () {
ReduseMenuSizeWhenWeDontHavePlace();
});
}
$( window ).resize(function() {
ReduseMenuSizeWhenWeDontHavePlace();
});
}
});
});jQuery(function($) {
$( document ).on( 's123.page.ready', function( event ) {
var layoutNUM = $('#layoutNUM').val();
if (layoutNUM=='15') {
if ($('.inside_page').length==0) {
var fixedMenuAfterFirstScroll = $(window).height()-$('#mainNav').height();
} else {
var fixedMenuAfterFirstScroll = 0;
}
$('#mainNav').affix({
offset: {
top: fixedMenuAfterFirstScroll
}
});
if ($('.home_page').length !== 0) {
$('#mainNav').off('affix.bs.affix').on( 'affix.bs.affix', function () {
$('.navbar-fixed-top').css({
'position':'fixed',
'bottom':'auto',
'top':'0'
});
});
$('#mainNav').off('affix-top.bs.affix').on( 'affix-top.bs.affix', function () {
$('.navbar-fixed-top').css({
'position':'absolute',
'bottom':'0',
'top':'auto'
});
});
}
$('body').scrollspy({
target: '#mainNav',
offset: $('#mainNav').height()
});
if (typeof document.fonts === 'undefined' || typeof document.fonts.ready === 'undefined' || typeof document.fonts.ready.then === 'undefined') {
setTimeout(function() {
ReduseMenuSizeWhenWeDontHavePlace();
},150);
} else {
document.fonts.ready.then(function () {
ReduseMenuSizeWhenWeDontHavePlace();
});
}
$( window ).resize(function() {
ReduseMenuSizeWhenWeDontHavePlace();
});
}
});
});jQuery(function($) {
$( document ).on( 's123.page.ready', function( event ) {
var layoutNUM = $('#layoutNUM').val();
if (layoutNUM=='20') {
var topMenuHeight = $('#mainNav').height();
if ($('.inside_page').length==0) {
var beforeScrollMenuHeight = $(window).height();
} else {
var beforeScrollMenuHeight = 0;
}
$('body').scrollspy({
target: '#mainNav',
offset: 0 //Must be 0 so the second page (if he is short) will be show
});
$('#mainNav').affix({
offset: {
top: beforeScrollMenuHeight
}
});
if ($('.home_page').length !== 0) {
$('#mainNav').off('affix.bs.affix').on( 'affix.bs.affix', function () {
$('.navbar-fixed-top').css({
'position':'fixed',
'bottom':'auto',
'top':'0'
});
});
$('#mainNav').off('affix-top.bs.affix').on( 'affix-top.bs.affix', function () {
$('.navbar-fixed-top').css({
'position':'absolute',
'bottom':'-'+topMenuHeight+'px',
'top':'auto'
});
});
}
if (typeof document.fonts === 'undefined' || typeof document.fonts.ready === 'undefined' || typeof document.fonts.ready.then === 'undefined') {
setTimeout(function() {
ReduseMenuSizeWhenWeDontHavePlace();
},150);
} else {
document.fonts.ready.then(function () {
ReduseMenuSizeWhenWeDontHavePlace();
});
}
$( window ).resize(function() {
ReduseMenuSizeWhenWeDontHavePlace();
});
}
});
});jQuery(function($) {
$( document ).on( 's123.page.ready', function( event ) {
var layoutNUM = $('#layoutNUM').val();
if (layoutNUM=='3' || layoutNUM=='11') {
$("#menu-toggle,#smallSidebar").off('click').click(function(e) {
e.preventDefault();
e.stopPropagation();
$("#header").toggleClass("active");
layout3_changeBarsIcon();
});
$("#top-section,.s123-modules-container,.s123-pages-container,footer").off('click.bodyCloseMenu').on('click.bodyCloseMenu', function (e) {
$("#header").removeClass("active");
layout3_changeBarsIcon();
});
$('body').scrollspy({
target: '#header'
});
$('#header #top-menu li').not('.dropdown-submenu').find('a').off('click').click(function() {
$("#menu-toggle").click();
});
if (typeof document.fonts === 'undefined' || typeof document.fonts.ready === 'undefined' || typeof document.fonts.ready.then === 'undefined') {
setTimeout(function() {
ReduseMenuSizeWhenWeDontHavePlaceHeight();
},150);
} else {
document.fonts.ready.then(function () {
ReduseMenuSizeWhenWeDontHavePlaceHeight();
});
}
$( window ).resize(function() {
ReduseMenuSizeWhenWeDontHavePlaceHeight();
});
}
});
});
function layout3_changeBarsIcon() {
if ($("#header").hasClass('active')) {
$("#menu-toggle").find('.fa').removeClass('fa-bars').addClass('fa-close');
} else {
$("#menu-toggle").find('.fa').removeClass('fa-close').addClass('fa-bars');
}
}jQuery(function($) {
$( document ).on( 's123.page.ready', function( event ) {
var layoutNUM = $('#layoutNUM').val();
if (layoutNUM=='4') {
$('body').scrollspy({
target: '#top-menu'
});
if (typeof document.fonts === 'undefined' || typeof document.fonts.ready === 'undefined' || typeof document.fonts.ready.then === 'undefined') {
setTimeout(function() {
ReduseMenuSizeWhenWeDontHavePlaceHeight();
},150);
} else {
document.fonts.ready.then(function () {
ReduseMenuSizeWhenWeDontHavePlaceHeight();
});
}
$( window ).resize(function() {
ReduseMenuSizeWhenWeDontHavePlaceHeight();
});
}
});
});jQuery(function($) {
CarouselModuleInitialize();
});
/**
* The function initialize the Carousel Module.
*/
function CarouselModuleInitialize() {
$( document ).on( 's123.page.ready', function( event ) {
var $sections = $('.s123-module-carousel');
$sections.each(function( index ) {
var $s = $(this);
categories = new ModuleLayoutCategories({
$items : $s.find('.carousel-category'),
$categoriesContainer : $s.find('.categories-panel'),
$filterButton : $s.find('.items-responsive-filter'),
$categories : $s.find('.items-categories-container li')
});
});
/**
* Carousel Module Initialize
* Source: /files/js/module.carousel.js
* Lines: 143-153
*/
if ($.isFunction($.fn['themePluginCarousel'])) {
$('[data-plugin-carousel]:not(.manual), .owl-carousel:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginCarousel(opts);
});
}
});
}jQuery(function($) {
VideoModuleInitialize();
});
/**
* The function initialize the Video Module.
*/
function VideoModuleInitialize() {
$( document ).on( 's123.page.ready', function( event ) {
/**
* Gallery & Video modules using the same classes but need to get different
* settings, so we create a selector to choose only the galley modules.
* Note: if we choose also the video the magnificPopup wont work.
*/
var $section = $('section.s123-module-videos');
$($section).each(function( index ) {
var $sectionThis = $(this);
var $isotopeContainer = $sectionThis.find('.isotope-gallery-container');
var $isotopeFilter = $sectionThis.find('.filter');
/**
* Video Modules - Magnific Popup Initial
* Documentation : http://dimsemenov.com/plugins/magnific-popup/documentation.html
*/
$sectionThis.magnificPopup({
delegate: '.mfp-iframe:visible', // Isotope Filter
closeOnContentClick: true,
closeBtnInside: false,
tLoading: translations.loading, // Text that is displayed during loading
iframe: {
patterns: {
youtube: {
index: 'youtube.com/',
id: function(url) {
var matches = url.match(/[\\?\\&]v=([^\\?\\&]+)/);
if ( !matches || !matches[1] ) return null;
return matches[1];
},
src: '//www.youtube.com/embed/%id%?autoplay=1'
},
vimeo: {
index: 'vimeo.com/',
id: function(url) {
var matches = url.match(/(https?:\/\/)?(www.)?(player.)?vimeo.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/);
if ( !matches || !matches[5] ) return null;
return matches[5];
},
src: '//player.vimeo.com/video/%id%?autoplay=1'
}
}
},
gallery: {
enabled: true,
tClose: translations.closeEsc, // Alt text on close button
tPrev: translations.previousLeftArrowKey, // Alt text on left arrow
tNext: translations.NextRightArrowKey, // Alt text on right arrow
tCounter: '%curr% '+translations.of+' %total%' // Markup for "1 of 7" counter
},
image: {
tError: translations.imageCouldNotLoaded // Error message when image could not be loaded
}
});
gallery_SetImageWidth($sectionThis);
/**
* Gallery Modules - Isotope Initial
*/
$isotopeContainer.isotope({
itemSelector: '.s123-module-gallery .gallery-item-wrapper',
filter: '.all'
});
/**
* Fix Images Height & Position Problem - If the Isotope sort the images
* before they already load, there is a height & position images problem.
* Reproduce: Delete browser cache (images) >> Wizard >> Pages >> Gallery >> Edit >> Close.
* Explanations: http://blog.codebusters.pl/en/images-height-and-position-problem-masonry-isotope/
* Documentations: http://isotope.metafizzy.co/layout.html#imagesloaded
*/
$isotopeContainer.imagesLoaded().progress( function( instance, image ) {
$isotopeContainer.isotope('layout');
$(image.img).css({visibility:'visible'});
});
$isotopeFilter.find('a').click(function () {
var filter = $(this).attr('data-filter');
$isotopeContainer.isotope({ filter: filter });
$isotopeFilter.find('a').parent().removeClass('active');
$(this).parent().addClass('active');
return false;
});
$(window).resize(function (event) {
var $section = $('section.s123-module-videos');
$($section).each(function( index ) {
var $sectionThis = $(this);
var $isotopeContainer = $sectionThis.find('.isotope-gallery-container');
gallery_SetImageWidth($sectionThis);
});
});
});
});
}jQuery(function($) {
GalleryModuleInitialize();
});
/**
* The function initialize the Gallery Module.
*/
function GalleryModuleInitialize() {
$( document ).on( 's123.page.ready', function( event ) {
/**
* Gallery & Video modules using the same classes but need to get different
* settings, so we create a selector to choose only the galley modules.
* Note: if we choose also the video the magnificPopup wont work.
*/
var $section = $('section.s123-module-gallery.isotope-gallery:not(.s123-module-videos)');
$section.each(function( index ) {
var $sectionThis = $(this);
var $isotopeContainer = $sectionThis.find('.isotope-gallery-container');
var $isotopeFilter = $sectionThis.find('.filter');
/**
* Gallery Modules - Magnific Popup Initial
* Documentation : http://dimsemenov.com/plugins/magnific-popup/documentation.html
*/
$sectionThis.magnificPopup({
mainClass: 'mfp-module-gallery',
delegate: '.mfp-image:visible', // Isotope Filter
closeOnContentClick: true,
closeBtnInside: false,
tLoading: translations.loading, // Text that is displayed during loading
gallery: {
enabled: true,
tClose: translations.closeEsc, // Alt text on close button
tPrev: translations.previousLeftArrowKey, // Alt text on left arrow
tNext: translations.NextRightArrowKey, // Alt text on right arrow
tCounter: '%curr% '+translations.of+' %total%' // Markup for "1 of 7" counter
},
image: {
markup: '
'+
''+
''+
'
'+
''+
''+
''+
'
'+
'
',
titleSrc: 'data-caption',
tError: translations.imageCouldNotLoaded // Error message when image could not be loaded
},
iframe: {
/**
* Magnific Popup doesn't show the caption on IFrames so we add it manually
* Source: https://stackoverflow.com/a/22023434/469161
*/
markup: '
' +
'' +
'' +
'' +
'
',
patterns: {
youtube: {
index: 'youtube.com/',
id: function(url) {
var matches = url.match(/[\\?\\&]v=([^\\?\\&]+)/);
if ( !matches || !matches[1] ) return null;
return matches[1];
},
src: '//www.youtube.com/embed/%id%?autoplay=1'
},
vimeo: {
index: 'vimeo.com/',
id: function(url) {
var matches = url.match(/(https?:\/\/)?(www.)?(player.)?vimeo.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/);
if ( !matches || !matches[5] ) return null;
return matches[5];
},
src: '//player.vimeo.com/video/%id%?autoplay=1'
},
site123: {
index: $GLOBALS['cdn-user-files'],
id: function( url ) {
/**
* Mobile Handler - The auto-play is not working at mobile
* if the video is not muted, so we disable it.
*/
if ( isMobile.any() ) url += '&autoplay=0';
return url;
},
src: '/include/globalVideoPlayer.php?cad=1&url=%id%'
},
site123Processing: {
index: '/files/images/video-processing.png',
id: function( url ) {
/**
* Mobile Handler - The auto-play is not working at mobile
* if the video is not muted, so we disable it.
*/
if ( isMobile.any() ) url += '&autoplay=0';
return url;
},
src: '/include/globalVideoPlayer.php?cad=1&url=%id%'
}
}
},
callbacks: {
elementParse: function( item ) {
if( item.el.data('type') === 'video' ) {
item.type = 'iframe';
} else {
item.type = 'image';
}
},
markupParse: function(template, values, item) {
/**
* Magnific Popup doesn't show the caption on IFrames so we add it manually
* Source: https://stackoverflow.com/a/22023434/469161
*/
values.title = item.el.data('caption');
/**
* Prevent closing the pop-up when the user clicks on caption, I didn't found
* a good event to handle it for all medias (including videos) so I use timeout.
*/
setTimeout(function(){
$('.mfp-title').off('click').click(function( event ) {
event.stopPropagation();
});
},500);
if ( !this.mp_currentPageUrl ) this.mp_currentPageUrl = window.location.href;
window.history.replaceState(this.mp_currentPageUrl,'Title',item.el.data('image-page-url'));
},
updateStatus: function( data ) {
var $bar = $('.mfp-bottom-bar');
var $close = $('.mfp-caption-close');
$bar.show();
$close .off('click').on('click',function( event ) {
event.stopPropagation();
$bar.hide();
});
$bar.height() > 50 ? $close .show() : $close .hide();
},
close: function(item) {
window.history.replaceState('','Title',this.mp_currentPageUrl);
}
}
});
gallery_SetImageWidth($sectionThis);
/**
* Gallery Modules - Isotope Initial
*/
$isotopeContainer.isotope({
itemSelector: '.s123-module-gallery .gallery-item-wrapper'
});
if ( $isotopeFilter.length !== 0 ) {
var $firstCategory = $isotopeFilter.find('> li > a').first();
$isotopeContainer.isotope({
filter: function() {
return gallery_Filter($(this),$firstCategory.attr('data-filter'));
}
});
$firstCategory.parent().addClass('active');
}
/**
* Fix Images Height & Position Problem - If the Isotope sort the images
* before they already load, there is a height & position images problem.
* Reproduce: Delete browser cache (images) >> Wizard >> Pages >> Gallery >> Edit >> Close.
* Explanations: http://blog.codebusters.pl/en/images-height-and-position-problem-masonry-isotope/
* Documentations: http://isotope.metafizzy.co/layout.html#imagesloaded
*/
$isotopeContainer.imagesLoaded().progress( function( instance, image ) {
$isotopeContainer.isotope('layout');
$(image.img).css({visibility:'visible'});
});
$isotopeFilter.find('a').click(function () {
var filter = $(this).attr('data-filter');
$isotopeContainer.isotope({
filter: function() {
return gallery_Filter($(this),filter);
}
});
$isotopeFilter.find('a').parent().removeClass('active');
$(this).parent().addClass('active');
return false;
});
$(window).resize(function (event) {
var $section = $('section.s123-module-gallery.isotope-gallery:not(.s123-module-videos)');
$section.each(function( index ) {
var $sectionThis = $(this);
var $isotopeContainer = $sectionThis.find('.isotope-gallery-container');
gallery_SetImageWidth($sectionThis);
});
});
});
});
}
/**
* The function filter the items related to the selected category.
* We create a custom filter function because we like to filter
* the items via data-attributes and not by class.
*/
function gallery_Filter( $item, filter ) {
return $item.attr('data-filter') == filter || filter == 's123-g-show-all';
}
function gallery_DecideNumberOfImageByScreenWidth($sectionThis) {
var screen = $sectionThis.find('.isotope-gallery-container').width();
if (screen<=400) {
return 1;
}
if (screen<=768) {
return 2;
}
if (screen<=992) {
return 3;
}
if (screen<=1600) {
return 3;
}
if (screen>1600) {
return 4;
}
}
function gallery_SetImageWidth($sectionThis) {
var imageWidth = Math.floor($sectionThis.find('.isotope-gallery-container').width()/gallery_DecideNumberOfImageByScreenWidth($sectionThis));
if ($sectionThis.hasClass('layout-1')) {
imageWidth = imageWidth - 10;
}
$sectionThis.find('.gallery-item-wrapper').width(imageWidth);
}jQuery(function($) {
GalleryModuleInitialize_Layout4();
});
/**
* The function initialize the Gallery Module.
*/
function GalleryModuleInitialize_Layout4() {
$( document ).on( 's123.page.ready', function( event ) {
/**
* Gallery & Video modules using the same classes but need to get different
* settings, so we create a selector to choose only the galley modules.
* Note: if we choose also the video the magnificPopup wont work.
*/
var $section = $('section.s123-module-gallery.layout-4:not(.s123-module-videos)');
$section.each(function( index ) {
var $sectionThis = $(this);
var $categories = $sectionThis.find('.filter li');
var $images = $sectionThis.find('.gallery-image');
/**
* Gallery Modules - Magnific Popup Initial
* Documentation : http://dimsemenov.com/plugins/magnific-popup/documentation.html
*/
$sectionThis.magnificPopup({
mainClass: 'mfp-module-gallery',
delegate: '.mfp-image:visible', // Categories Filter
closeOnContentClick: true,
closeBtnInside: false,
tLoading: translations.loading, // Text that is displayed during loading
gallery: {
enabled: true,
tClose: translations.closeEsc, // Alt text on close button
tPrev: translations.previousLeftArrowKey, // Alt text on left arrow
tNext: translations.NextRightArrowKey, // Alt text on right arrow
tCounter: '%curr% '+translations.of+' %total%' // Markup for "1 of 7" counter
},
image: {
markup: '
'+
''+
''+
'
'+
''+
''+
''+
'
'+
'
',
titleSrc: 'data-caption',
tError: translations.imageCouldNotLoaded // Error message when image could not be loaded
},
iframe: {
/**
* Magnific Popup doesn't show the caption on IFrames so we add it manually
* Source: https://stackoverflow.com/a/22023434/469161
*/
markup: '
' +
'' +
'' +
'' +
'
',
patterns: {
youtube: {
index: 'youtube.com/',
id: function(url) {
var matches = url.match(/[\\?\\&]v=([^\\?\\&]+)/);
if ( !matches || !matches[1] ) return null;
return matches[1];
},
src: '//www.youtube.com/embed/%id%?autoplay=1'
},
vimeo: {
index: 'vimeo.com/',
id: function(url) {
var matches = url.match(/(https?:\/\/)?(www.)?(player.)?vimeo.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/);
if ( !matches || !matches[5] ) return null;
return matches[5];
},
src: '//player.vimeo.com/video/%id%?autoplay=1'
},
site123: {
index: $GLOBALS['cdn-user-files'],
id: function( url ) {
/**
* Mobile Handler - The auto-play is not working at mobile
* if the video is not muted, so we disable it.
*/
if ( isMobile.any() ) url += '&autoplay=0';
return url;
},
src: '/include/globalVideoPlayer.php?cad=1&url=%id%'
},
site123Processing: {
index: '/files/images/video-processing.png',
id: function( url ) {
/**
* Mobile Handler - The auto-play is not working at mobile
* if the video is not muted, so we disable it.
*/
if ( isMobile.any() ) url += '&autoplay=0';
return url;
},
src: '/include/globalVideoPlayer.php?cad=1&url=%id%'
}
}
},
callbacks: {
elementParse: function( item ) {
if( item.el.data('type') === 'video' ) {
item.type = 'iframe';
} else {
item.type = 'image';
}
},
markupParse: function(template, values, item) {
/**
* Magnific Popup doesn't show the caption on IFrames so we add it manually
* Source: https://stackoverflow.com/a/22023434/469161
*/
values.title = item.el.data('caption');
/**
* Prevent closing the pop-up when the user clicks on caption, I didn't found
* a good event to handle it for all medias (including videos) so I use timeout.
*/
setTimeout(function(){
$('.mfp-title').off('click').click(function( event ) {
event.stopPropagation();
});
},500);
if ( !this.mp_currentPageUrl ) this.mp_currentPageUrl = window.location.href;
window.history.replaceState(this.mp_currentPageUrl,'Title',item.el.data('image-page-url'));
},
updateStatus: function( data ) {
var $bar = $('.mfp-bottom-bar');
var $close = $('.mfp-caption-close');
$bar.show();
$close .off('click').on('click',function( event ) {
event.stopPropagation();
$bar.hide();
});
$bar.height() > 50 ? $close .show() : $close .hide();
},
close: function(item) {
window.history.replaceState('','Title',this.mp_currentPageUrl);
}
}
});
$categories.off('click').on('click',function ( event, initialize ) {
var $category = $(this);
$categories.removeClass('active');
$category.addClass('active');
$sectionThis.css({ minHeight: $sectionThis.height() });
var $filtered = $category.data('filter') == 's123-g-show-all' ? $images : $images.filter('[data-filter=' + $category.data('filter') + ']');
if ( initialize ) {
$images.hide();
$filtered.show();
$sectionThis.css({ minHeight: '' });
$(window).trigger('scroll');
} else {
$images.fadeOut(200).promise().done( function() {
$filtered.fadeIn(200);
$sectionThis.css({ minHeight: '' });
$(window).trigger('scroll');
});
}
return false;
});
$categories.first().trigger('click',true);
});
});
}jQuery(function($) {
GalleryModuleInitialize_Layout5();
});
/**
* The function initialize the Gallery Module.
*/
function GalleryModuleInitialize_Layout5() {
$( document ).on( 's123.page.ready', function( event ) {
/**
* Gallery & Video modules using the same classes but need to get different
* settings, so we create a selector to choose only the galley modules.
* Note: if we choose also the video the magnificPopup wont work.
*/
var $section = $('section.s123-module-gallery.layout-5:not(.s123-module-videos)');
$section.each(function( index ) {
var $sectionThis = $(this);
var $categories = $sectionThis.find('.filter li');
var $images = $sectionThis.find('.gallery-image');
/**
* Gallery Modules - Magnific Popup Initial
* Documentation : http://dimsemenov.com/plugins/magnific-popup/documentation.html
*/
$sectionThis.magnificPopup({
mainClass: 'mfp-module-gallery',
delegate: '.mfp-image:visible', // Categories Filter
closeOnContentClick: true,
closeBtnInside: false,
tLoading: translations.loading, // Text that is displayed during loading
gallery: {
enabled: true,
tClose: translations.closeEsc, // Alt text on close button
tPrev: translations.previousLeftArrowKey, // Alt text on left arrow
tNext: translations.NextRightArrowKey, // Alt text on right arrow
tCounter: '%curr% '+translations.of+' %total%' // Markup for "1 of 7" counter
},
image: {
markup: '
'+
''+
''+
'
'+
''+
''+
''+
'
'+
'
',
titleSrc: 'data-caption',
tError: translations.imageCouldNotLoaded // Error message when image could not be loaded
},
iframe: {
/**
* Magnific Popup doesn't show the caption on IFrames so we add it manually
* Source: https://stackoverflow.com/a/22023434/469161
*/
markup: '
' +
'' +
'' +
'' +
'
',
patterns: {
youtube: {
index: 'youtube.com/',
id: function(url) {
var matches = url.match(/[\\?\\&]v=([^\\?\\&]+)/);
if ( !matches || !matches[1] ) return null;
return matches[1];
},
src: '//www.youtube.com/embed/%id%?autoplay=1'
},
vimeo: {
index: 'vimeo.com/',
id: function(url) {
var matches = url.match(/(https?:\/\/)?(www.)?(player.)?vimeo.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/);
if ( !matches || !matches[5] ) return null;
return matches[5];
},
src: '//player.vimeo.com/video/%id%?autoplay=1'
},
site123: {
index: $GLOBALS['cdn-user-files'],
id: function( url ) {
/**
* Mobile Handler - The auto-play is not working at mobile
* if the video is not muted, so we disable it.
*/
if ( isMobile.any() ) url += '&autoplay=0';
return url;
},
src: '/include/globalVideoPlayer.php?cad=1&url=%id%'
},
site123Processing: {
index: '/files/images/video-processing.png',
id: function( url ) {
/**
* Mobile Handler - The auto-play is not working at mobile
* if the video is not muted, so we disable it.
*/
if ( isMobile.any() ) url += '&autoplay=0';
return url;
},
src: '/include/globalVideoPlayer.php?cad=1&url=%id%'
}
}
},
callbacks: {
elementParse: function( item ) {
if( item.el.data('type') === 'video' ) {
item.type = 'iframe';
} else {
item.type = 'image';
}
},
markupParse: function(template, values, item) {
/**
* Magnific Popup doesn't show the caption on IFrames so we add it manually
* Source: https://stackoverflow.com/a/22023434/469161
*/
values.title = item.el.data('caption');
/**
* Prevent closing the pop-up when the user clicks on caption, I didn't found
* a good event to handle it for all medias (including videos) so I use timeout.
*/
setTimeout(function(){
$('.mfp-title').off('click').click(function( event ) {
event.stopPropagation();
});
},500);
if ( !this.mp_currentPageUrl ) this.mp_currentPageUrl = window.location.href;
window.history.replaceState(this.mp_currentPageUrl,'Title',item.el.data('image-page-url'));
},
updateStatus: function( data ) {
var $bar = $('.mfp-bottom-bar');
var $close = $('.mfp-caption-close');
$bar.show();
$close .off('click').on('click',function( event ) {
event.stopPropagation();
$bar.hide();
});
$bar.height() > 50 ? $close .show() : $close .hide();
},
close: function(item) {
window.history.replaceState('','Title',this.mp_currentPageUrl);
}
}
});
$categories.off('click').on('click',function ( event, initialize ) {
var $category = $(this);
$categories.removeClass('active');
$category.addClass('active');
$sectionThis.css({ minHeight: $sectionThis.height() });
var $filtered = $category.data('filter') == 's123-g-show-all' ? $images : $images.filter('[data-filter=' + $category.data('filter') + ']');
if ( initialize ) {
$images.hide();
$filtered.show();
$sectionThis.css({ minHeight: '' });
$(window).trigger('scroll');
} else {
$images.fadeOut(200).promise().done( function() {
$filtered.fadeIn(200);
$sectionThis.css({ minHeight: '' });
$(window).trigger('scroll');
});
}
return false;
});
$categories.first().trigger('click',true);
});
});
}/*!
* Flickity PACKAGED v2.0.10
* Touch, responsive, flickable carousels
*
* Licensed GPLv3 for open source use
* or Flickity Commercial License for commercial use
*
* http://flickity.metafizzy.co
* Copyright 2017 Metafizzy
*/
!function(t,e){"function"==typeof define&&define.amd?define("jquery-bridget/jquery-bridget",["jquery"],function(i){return e(t,i)}):"object"==typeof module&&module.exports?module.exports=e(t,require("jquery")):t.jQueryBridget=e(t,t.jQuery)}(window,function(t,e){"use strict";function i(i,o,a){function h(t,e,n){var s,o="$()."+i+'("'+e+'")';return t.each(function(t,h){var l=a.data(h,i);if(!l)return void r(i+" not initialized. Cannot call methods, i.e. "+o);var c=l[e];if(!c||"_"==e.charAt(0))return void r(o+" is not a valid method");var d=c.apply(l,n);s=void 0===s?d:s}),void 0!==s?s:t}function l(t,e){t.each(function(t,n){var s=a.data(n,i);s?(s.option(e),s._init()):(s=new o(n,e),a.data(n,i,s))})}a=a||e||t.jQuery,a&&(o.prototype.option||(o.prototype.option=function(t){a.isPlainObject(t)&&(this.options=a.extend(!0,this.options,t))}),a.fn[i]=function(t){if("string"==typeof t){var e=s.call(arguments,1);return h(this,t,e)}return l(this,t),this},n(a))}function n(t){!t||t&&t.bridget||(t.bridget=i)}var s=Array.prototype.slice,o=t.console,r="undefined"==typeof o?function(){}:function(t){o.error(t)};return n(e||t.jQuery),i}),function(t,e){"function"==typeof define&&define.amd?define("ev-emitter/ev-emitter",e):"object"==typeof module&&module.exports?module.exports=e():t.EvEmitter=e()}("undefined"!=typeof window?window:this,function(){function t(){}var e=t.prototype;return e.on=function(t,e){if(t&&e){var i=this._events=this._events||{},n=i[t]=i[t]||[];return n.indexOf(e)==-1&&n.push(e),this}},e.once=function(t,e){if(t&&e){this.on(t,e);var i=this._onceEvents=this._onceEvents||{},n=i[t]=i[t]||{};return n[e]=!0,this}},e.off=function(t,e){var i=this._events&&this._events[t];if(i&&i.length){var n=i.indexOf(e);return n!=-1&&i.splice(n,1),this}},e.emitEvent=function(t,e){var i=this._events&&this._events[t];if(i&&i.length){i=i.slice(0),e=e||[];for(var n=this._onceEvents&&this._onceEvents[t],s=0;s1&&(t=e.modulo(t,this.slideableWidth),t-=this.slideableWidth,this.shiftWrapCells(t)),t+=this.cursorPosition,t=this.options.rightToLeft&&o?-t:t;var i=this.getPositionValue(t);this.slider.style[o]=this.isAnimating?"translate3d("+i+",0,0)":"translateX("+i+")";var n=this.slides[0];if(n){var s=-this.x-n.target,r=s/this.slidesWidth;this.dispatchEvent("scroll",null,[r,s])}},s.positionSliderAtSelected=function(){this.cells.length&&(this.x=-this.selectedSlide.target,this.positionSlider())},s.getPositionValue=function(t){return this.options.percentPosition?.01*Math.round(t/this.size.innerWidth*1e4)+"%":Math.round(t)+"px"},s.settle=function(t){this.isPointerDown||Math.round(100*this.x)!=Math.round(100*t)||this.restingFrames++,this.restingFrames>2&&(this.isAnimating=!1,delete this.isFreeScrolling,this.positionSlider(),this.dispatchEvent("settle"))},s.shiftWrapCells=function(t){var e=this.cursorPosition+t;this._shiftCells(this.beforeShiftCells,e,-1);var i=this.size.innerWidth-(t+this.slideableWidth+this.cursorPosition);this._shiftCells(this.afterShiftCells,i,1)},s._shiftCells=function(t,e,i){for(var n=0;n0?i:0;s.wrapShift(o),e-=s.size.outerWidth}},s._unshiftCells=function(t){if(t&&t.length)for(var e=0;e0){var i=this.cells[t-1];e=i.x+i.size.outerWidth}for(var n=this.cells.length,s=t;s0;){var s=this.cells[e];if(!s)break;n.push(s),e+=i,t-=s.size.outerWidth}return n},p._containSlides=function(){if(this.options.contain&&!this.options.wrapAround&&this.cells.length){var t=this.options.rightToLeft,e=t?"marginRight":"marginLeft",i=t?"marginLeft":"marginRight",n=this.slideableWidth-this.getLastCell().size[i],s=n1;if(!i)return t;var s=n.modulo(t,e),o=Math.abs(s-this.selectedIndex),r=Math.abs(s+e-this.selectedIndex),a=Math.abs(s-e-this.selectedIndex);!this.isDragSelect&&r=e&&(this.x+=this.slideableWidth)},p.previous=function(t,e){this.select(this.selectedIndex-1,t,e)},p.next=function(t,e){this.select(this.selectedIndex+1,t,e)},p.updateSelectedSlide=function(){var t=this.slides[this.selectedIndex];t&&(this.unselectSelectedSlide(),this.selectedSlide=t,t.select(),this.selectedCells=t.cells,this.selectedElements=t.getCellElements(),this.selectedCell=t.cells[0],this.selectedElement=this.selectedElements[0])},p.unselectSelectedSlide=function(){this.selectedSlide&&this.selectedSlide.unselect()},p.selectCell=function(t,e,i){var n;"number"==typeof t?n=this.cells[t]:("string"==typeof t&&(t=this.element.querySelector(t)),n=this.getCell(t));for(var s=0;n&&s *"),this.getCell(t))},p.getAdjacentCellElements=function(t,e){if(!t)return this.selectedSlide.getCellElements();e=void 0===e?this.selectedIndex:e;var i=this.slides.length;if(1+2*t>=i)return this.getCellElements();for(var s=[],o=e-t;o<=e+t;o++){var r=this.options.wrapAround?n.modulo(o,i):o,a=this.slides[r];a&&(s=s.concat(a.getCellElements()))}return s},p.uiChange=function(){this.emitEvent("uiChange")},p.childUIPointerDown=function(t){this.emitEvent("childUIPointerDown",[t])},p.onresize=function(){this.watchCSS(),this.resize()},n.debounceMethod(h,"onresize",150),p.resize=function(){if(this.isActive){this.getSize(),this.options.wrapAround&&(this.x=n.modulo(this.x,this.slideableWidth)),this.positionCells(),this._getWrapShiftCells(),this.setGallerySize(),this.emitEvent("resize");var t=this.selectedElements&&this.selectedElements[0];this.selectCell(t,!1,!0)}},p.watchCSS=function(){var t=this.options.watchCSS;if(t){var e=c(this.element,":after").content;e.indexOf("flickity")!=-1?this.activate():this.deactivate()}},p.onkeydown=function(t){if(this.options.accessibility&&(!document.activeElement||document.activeElement==this.element))if(37==t.keyCode){var e=this.options.rightToLeft?"next":"previous";this.uiChange(),this[e]()}else if(39==t.keyCode){var i=this.options.rightToLeft?"previous":"next";this.uiChange(),this[i]()}},p.deactivate=function(){this.isActive&&(this.element.classList.remove("flickity-enabled"),this.element.classList.remove("flickity-rtl"),this.cells.forEach(function(t){t.destroy()}),this.unselectSelectedSlide(),this.element.removeChild(this.viewport),a(this.slider.children,this.element),this.options.accessibility&&(this.element.removeAttribute("tabIndex"),this.element.removeEventListener("keydown",this)),this.isActive=!1,this.emitEvent("deactivate"))},p.destroy=function(){this.deactivate(),t.removeEventListener("resize",this),this.emitEvent("destroy"),l&&this.$element&&l.removeData(this.element,"flickity"),delete this.element.flickityGUID,delete f[this.guid]},n.extend(p,r),h.data=function(t){t=n.getQueryElement(t);var e=t&&t.flickityGUID;return e&&f[e]},n.htmlInit(h,"flickity"),l&&l.bridget&&l.bridget("flickity",h),h.setJQuery=function(t){l=t},h.Cell=s,h}),function(t,e){"function"==typeof define&&define.amd?define("unipointer/unipointer",["ev-emitter/ev-emitter"],function(i){return e(t,i)}):"object"==typeof module&&module.exports?module.exports=e(t,require("ev-emitter")):t.Unipointer=e(t,t.EvEmitter)}(window,function(t,e){function i(){}function n(){}var s=n.prototype=Object.create(e.prototype);s.bindStartEvent=function(t){this._bindStartEvent(t,!0)},s.unbindStartEvent=function(t){this._bindStartEvent(t,!1)},s._bindStartEvent=function(e,i){i=void 0===i||!!i;var n=i?"addEventListener":"removeEventListener";t.PointerEvent?e[n]("pointerdown",this):(e[n]("mousedown",this),e[n]("touchstart",this))},s.handleEvent=function(t){var e="on"+t.type;this[e]&&this[e](t)},s.getTouch=function(t){for(var e=0;e3||Math.abs(t.y)>3},n.pointerUp=function(t,e){this.emitEvent("pointerUp",[t,e]),this._dragPointerUp(t,e)},n._dragPointerUp=function(t,e){this.isDragging?this._dragEnd(t,e):this._staticClick(t,e)},n._dragStart=function(t,i){this.isDragging=!0,this.dragStartPoint=e.getPointerPoint(i),this.isPreventingClicks=!0,this.dragStart(t,i)},n.dragStart=function(t,e){this.emitEvent("dragStart",[t,e])},n._dragMove=function(t,e,i){this.isDragging&&this.dragMove(t,e,i)},n.dragMove=function(t,e,i){t.preventDefault(),this.emitEvent("dragMove",[t,e,i])},n._dragEnd=function(t,e){this.isDragging=!1,setTimeout(function(){delete this.isPreventingClicks}.bind(this)),this.dragEnd(t,e)},n.dragEnd=function(t,e){this.emitEvent("dragEnd",[t,e])},n.onclick=function(t){this.isPreventingClicks&&t.preventDefault()},n._staticClick=function(t,e){if(!this.isIgnoringMouseUp||"mouseup"!=t.type){var i=t.target.nodeName;"INPUT"!=i&&"TEXTAREA"!=i||t.target.focus(),this.staticClick(t,e),"mouseup"!=t.type&&(this.isIgnoringMouseUp=!0,setTimeout(function(){delete this.isIgnoringMouseUp}.bind(this),400))}},n.staticClick=function(t,e){this.emitEvent("staticClick",[t,e])},i.getPointerPoint=e.getPointerPoint,i}),function(t,e){"function"==typeof define&&define.amd?define("flickity/js/drag",["./flickity","unidragger/unidragger","fizzy-ui-utils/utils"],function(i,n,s){return e(t,i,n,s)}):"object"==typeof module&&module.exports?module.exports=e(t,require("./flickity"),require("unidragger"),require("fizzy-ui-utils")):t.Flickity=e(t,t.Flickity,t.Unidragger,t.fizzyUIUtils)}(window,function(t,e,i,n){function s(t){var e="touchstart"==t.type,i="touch"==t.pointerType,n=d[t.target.nodeName];return e||i||n}function o(){return{x:t.pageXOffset,y:t.pageYOffset}}n.extend(e.defaults,{draggable:!0,dragThreshold:3}),e.createMethods.push("_createDrag");var r=e.prototype;n.extend(r,i.prototype),r._touchActionValue="pan-y";var a="createTouch"in document,h=!1;r._createDrag=function(){this.on("activate",this.bindDrag),this.on("uiChange",this._uiChangeDrag),this.on("childUIPointerDown",this._childUIPointerDownDrag),this.on("deactivate",this.unbindDrag),a&&!h&&(t.addEventListener("touchmove",function(){}),h=!0)},r.bindDrag=function(){this.options.draggable&&!this.isDragBound&&(this.element.classList.add("is-draggable"),this.handles=[this.viewport],this.bindHandles(),this.isDragBound=!0)},r.unbindDrag=function(){this.isDragBound&&(this.element.classList.remove("is-draggable"),this.unbindHandles(),delete this.isDragBound)},r._uiChangeDrag=function(){delete this.isFreeScrolling},r._childUIPointerDownDrag=function(t){t.preventDefault(),this.pointerDownFocus(t)};var l={TEXTAREA:!0,INPUT:!0,OPTION:!0},c={radio:!0,checkbox:!0,button:!0,submit:!0,image:!0,file:!0};r.pointerDown=function(e,i){var n=l[e.target.nodeName]&&!c[e.target.type];if(n)return this.isPointerDown=!1,void delete this.pointerIdentifier;this._dragPointerDown(e,i);var s=document.activeElement;s&&s.blur&&s!=this.element&&s!=document.body&&s.blur(),this.pointerDownFocus(e),this.dragX=this.x,this.viewport.classList.add("is-pointer-down"),this._bindPostStartEvents(e),this.pointerDownScroll=o(),t.addEventListener("scroll",this),this.dispatchEvent("pointerDown",e,[i])},r.pointerDownFocus=function(e){var i=s(e);if(this.options.accessibility&&!i){var n=t.pageYOffset;this.element.focus(),t.pageYOffset!=n&&t.scrollTo(t.pageXOffset,n)}};var d={INPUT:!0,SELECT:!0};return r.canPreventDefaultOnPointerDown=function(t){var e=s(t);return!e},r.hasDragStarted=function(t){return Math.abs(t.x)>this.options.dragThreshold},r.pointerUp=function(t,e){delete this.isTouchScrolling,this.viewport.classList.remove("is-pointer-down"),this.dispatchEvent("pointerUp",t,[e]),this._dragPointerUp(t,e)},r.pointerDone=function(){t.removeEventListener("scroll",this),delete this.pointerDownScroll},r.dragStart=function(e,i){this.dragStartPosition=this.x,this.startAnimation(),t.removeEventListener("scroll",this),this.dispatchEvent("dragStart",e,[i])},r.pointerMove=function(t,e){var i=this._dragPointerMove(t,e);this.dispatchEvent("pointerMove",t,[e,i]),this._dragMove(t,e,i)},r.dragMove=function(t,e,i){t.preventDefault(),this.previousDragX=this.dragX;var n=this.options.rightToLeft?-1:1,s=this.dragStartPosition+i.x*n;if(!this.options.wrapAround&&this.slides.length){var o=Math.max(-this.slides[0].target,this.dragStartPosition);s=s>o?.5*(s+o):s;var r=Math.min(-this.getLastSlide().target,this.dragStartPosition);s=sthis.slides[0].target&&-n1,o=s?n.modulo(e,i):e,r=this.slides[o];if(!r)return null;var a=s?this.slideableWidth*Math.floor(e/i):0;return t-(r.target+a)},r.dragEndBoostSelect=function(){if(void 0===this.previousDragX||!this.dragMoveTime||new Date-this.dragMoveTime>100)return 0;var t=this.getSlideDistance(-this.dragX,this.selectedIndex),e=this.previousDragX-this.dragX;return t>0&&e>0?1:t<0&&e<0?-1:0},r.staticClick=function(t,e){var i=this.getParentCell(t.target),n=i&&i.element,s=i&&this.cells.indexOf(i);this.dispatchEvent("staticClick",t,[e,n,s])},r.onscroll=function(){var t=o(),e=this.pointerDownScroll.x-t.x,i=this.pointerDownScroll.y-t.y;(Math.abs(e)>3||Math.abs(i)>3)&&this._pointerDone()},e}),function(t,e){"function"==typeof define&&define.amd?define("tap-listener/tap-listener",["unipointer/unipointer"],function(i){return e(t,i)}):"object"==typeof module&&module.exports?module.exports=e(t,require("unipointer")):t.TapListener=e(t,t.Unipointer)}(window,function(t,e){function i(t){this.bindTap(t)}var n=i.prototype=Object.create(e.prototype);return n.bindTap=function(t){t&&(this.unbindTap(),this.tapElement=t,this._bindStartEvent(t,!0))},n.unbindTap=function(){this.tapElement&&(this._bindStartEvent(this.tapElement,!0),delete this.tapElement)},n.pointerUp=function(i,n){if(!this.isIgnoringMouseUp||"mouseup"!=i.type){var s=e.getPointerPoint(n),o=this.tapElement.getBoundingClientRect(),r=t.pageXOffset,a=t.pageYOffset,h=s.x>=o.left+r&&s.x<=o.right+r&&s.y>=o.top+a&&s.y<=o.bottom+a;if(h&&this.emitEvent("tap",[i,n]),"mouseup"!=i.type){this.isIgnoringMouseUp=!0;var l=this;setTimeout(function(){delete l.isIgnoringMouseUp},400)}}},n.destroy=function(){this.pointerDone(),this.unbindTap()},i}),function(t,e){"function"==typeof define&&define.amd?define("flickity/js/prev-next-button",["./flickity","tap-listener/tap-listener","fizzy-ui-utils/utils"],function(i,n,s){return e(t,i,n,s)}):"object"==typeof module&&module.exports?module.exports=e(t,require("./flickity"),require("tap-listener"),require("fizzy-ui-utils")):e(t,t.Flickity,t.TapListener,t.fizzyUIUtils)}(window,function(t,e,i,n){"use strict";function s(t,e){this.direction=t,this.parent=e,this._create()}function o(t){return"string"==typeof t?t:"M "+t.x0+",50 L "+t.x1+","+(t.y1+50)+" L "+t.x2+","+(t.y2+50)+" L "+t.x3+",50 L "+t.x2+","+(50-t.y2)+" L "+t.x1+","+(50-t.y1)+" Z"}var r="http://www.w3.org/2000/svg";s.prototype=new i,s.prototype._create=function(){this.isEnabled=!0,this.isPrevious=this.direction==-1;var t=this.parent.options.rightToLeft?1:-1;this.isLeft=this.direction==t;var e=this.element=document.createElement("button");e.className="flickity-prev-next-button",e.className+=this.isPrevious?" previous":" next",e.setAttribute("type","button"),this.disable(),e.setAttribute("aria-label",this.isPrevious?"previous":"next");var i=this.createSVG();e.appendChild(i),this.on("tap",this.onTap),this.parent.on("select",this.update.bind(this)),this.on("pointerDown",this.parent.childUIPointerDown.bind(this.parent))},s.prototype.activate=function(){this.bindTap(this.element),this.element.addEventListener("click",this),this.parent.element.appendChild(this.element)},s.prototype.deactivate=function(){this.parent.element.removeChild(this.element),i.prototype.destroy.call(this),this.element.removeEventListener("click",this)},s.prototype.createSVG=function(){var t=document.createElementNS(r,"svg");t.setAttribute("viewBox","0 0 100 100");var e=document.createElementNS(r,"path"),i=o(this.parent.options.arrowShape);return e.setAttribute("d",i),e.setAttribute("class","arrow"),this.isLeft||e.setAttribute("transform","translate(100, 100) rotate(180) "),t.appendChild(e),t},s.prototype.onTap=function(){if(this.isEnabled){this.parent.uiChange();var t=this.isPrevious?"previous":"next";this.parent[t]()}},s.prototype.handleEvent=n.handleEvent,s.prototype.onclick=function(){var t=document.activeElement;t&&t==this.element&&this.onTap()},s.prototype.enable=function(){this.isEnabled||(this.element.disabled=!1,this.isEnabled=!0)},s.prototype.disable=function(){this.isEnabled&&(this.element.disabled=!0,this.isEnabled=!1)},s.prototype.update=function(){var t=this.parent.slides;if(this.parent.options.wrapAround&&t.length>1)return void this.enable();var e=t.length?t.length-1:0,i=this.isPrevious?0:e,n=this.parent.selectedIndex==i?"disable":"enable";this[n]()},s.prototype.destroy=function(){this.deactivate()},n.extend(e.defaults,{prevNextButtons:!0,arrowShape:{x0:10,x1:60,y1:50,x2:70,y2:40,x3:30}}),e.createMethods.push("_createPrevNextButtons");var a=e.prototype;return a._createPrevNextButtons=function(){this.options.prevNextButtons&&(this.prevButton=new s((-1),this),this.nextButton=new s(1,this),this.on("activate",this.activatePrevNextButtons))},a.activatePrevNextButtons=function(){this.prevButton.activate(),this.nextButton.activate(),this.on("deactivate",this.deactivatePrevNextButtons)},a.deactivatePrevNextButtons=function(){this.prevButton.deactivate(),this.nextButton.deactivate(),this.off("deactivate",this.deactivatePrevNextButtons)},e.PrevNextButton=s,e}),function(t,e){"function"==typeof define&&define.amd?define("flickity/js/page-dots",["./flickity","tap-listener/tap-listener","fizzy-ui-utils/utils"],function(i,n,s){return e(t,i,n,s)}):"object"==typeof module&&module.exports?module.exports=e(t,require("./flickity"),require("tap-listener"),require("fizzy-ui-utils")):e(t,t.Flickity,t.TapListener,t.fizzyUIUtils)}(window,function(t,e,i,n){function s(t){this.parent=t,this._create()}s.prototype=new i,s.prototype._create=function(){this.holder=document.createElement("ol"),this.holder.className="flickity-page-dots",this.dots=[],this.on("tap",this.onTap),this.on("pointerDown",this.parent.childUIPointerDown.bind(this.parent))},s.prototype.activate=function(){this.setDots(),this.bindTap(this.holder),this.parent.element.appendChild(this.holder)},s.prototype.deactivate=function(){this.parent.element.removeChild(this.holder),i.prototype.destroy.call(this)},s.prototype.setDots=function(){var t=this.parent.slides.length-this.dots.length;t>0?this.addDots(t):t<0&&this.removeDots(-t)},s.prototype.addDots=function(t){for(var e=document.createDocumentFragment(),i=[];t;){var n=document.createElement("li");n.className="dot",e.appendChild(n),i.push(n),t--}this.holder.appendChild(e),this.dots=this.dots.concat(i)},s.prototype.removeDots=function(t){var e=this.dots.splice(this.dots.length-t,t);e.forEach(function(t){this.holder.removeChild(t)},this)},s.prototype.updateSelected=function(){this.selectedDot&&(this.selectedDot.className="dot"),this.dots.length&&(this.selectedDot=this.dots[this.parent.selectedIndex],this.selectedDot.className="dot is-selected")},s.prototype.onTap=function(t){var e=t.target;if("LI"==e.nodeName){this.parent.uiChange();var i=this.dots.indexOf(e);this.parent.select(i)}},s.prototype.destroy=function(){this.deactivate()},e.PageDots=s,n.extend(e.defaults,{pageDots:!0}),e.createMethods.push("_createPageDots");var o=e.prototype;return o._createPageDots=function(){this.options.pageDots&&(this.pageDots=new s(this),this.on("activate",this.activatePageDots),this.on("select",this.updateSelectedPageDots),this.on("cellChange",this.updatePageDots),this.on("resize",this.updatePageDots),this.on("deactivate",this.deactivatePageDots))},o.activatePageDots=function(){this.pageDots.activate()},o.updateSelectedPageDots=function(){this.pageDots.updateSelected()},o.updatePageDots=function(){this.pageDots.setDots()},o.deactivatePageDots=function(){this.pageDots.deactivate()},e.PageDots=s,e}),function(t,e){"function"==typeof define&&define.amd?define("flickity/js/player",["ev-emitter/ev-emitter","fizzy-ui-utils/utils","./flickity"],function(t,i,n){return e(t,i,n)}):"object"==typeof module&&module.exports?module.exports=e(require("ev-emitter"),require("fizzy-ui-utils"),require("./flickity")):e(t.EvEmitter,t.fizzyUIUtils,t.Flickity)}(window,function(t,e,i){function n(t){this.parent=t,this.state="stopped",o&&(this.onVisibilityChange=function(){this.visibilityChange()}.bind(this),this.onVisibilityPlay=function(){this.visibilityPlay()}.bind(this))}var s,o;"hidden"in document?(s="hidden",o="visibilitychange"):"webkitHidden"in document&&(s="webkitHidden",o="webkitvisibilitychange"),n.prototype=Object.create(t.prototype),n.prototype.play=function(){if("playing"!=this.state){var t=document[s];if(o&&t)return void document.addEventListener(o,this.onVisibilityPlay);this.state="playing",o&&document.addEventListener(o,this.onVisibilityChange),this.tick()}},n.prototype.tick=function(){if("playing"==this.state){var t=this.parent.options.autoPlay;t="number"==typeof t?t:3e3;var e=this;this.clear(),this.timeout=setTimeout(function(){e.parent.next(!0),e.tick()},t)}},n.prototype.stop=function(){this.state="stopped",this.clear(),o&&document.removeEventListener(o,this.onVisibilityChange)},n.prototype.clear=function(){clearTimeout(this.timeout)},n.prototype.pause=function(){"playing"==this.state&&(this.state="paused",this.clear())},n.prototype.unpause=function(){"paused"==this.state&&this.play()},n.prototype.visibilityChange=function(){var t=document[s];this[t?"pause":"unpause"]()},n.prototype.visibilityPlay=function(){this.play(),document.removeEventListener(o,this.onVisibilityPlay)},e.extend(i.defaults,{pauseAutoPlayOnHover:!0}),i.createMethods.push("_createPlayer");var r=i.prototype;return r._createPlayer=function(){this.player=new n(this),this.on("activate",this.activatePlayer),this.on("uiChange",this.stopPlayer),this.on("pointerDown",this.stopPlayer),this.on("deactivate",this.deactivatePlayer)},r.activatePlayer=function(){this.options.autoPlay&&(this.player.play(),this.element.addEventListener("mouseenter",this))},r.playPlayer=function(){this.player.play()},r.stopPlayer=function(){this.player.stop()},r.pausePlayer=function(){this.player.pause()},r.unpausePlayer=function(){this.player.unpause()},r.deactivatePlayer=function(){this.player.stop(),this.element.removeEventListener("mouseenter",this)},r.onmouseenter=function(){this.options.pauseAutoPlayOnHover&&(this.player.pause(),this.element.addEventListener("mouseleave",this))},r.onmouseleave=function(){this.player.unpause(),this.element.removeEventListener("mouseleave",this)},i.Player=n,i}),function(t,e){"function"==typeof define&&define.amd?define("flickity/js/add-remove-cell",["./flickity","fizzy-ui-utils/utils"],function(i,n){return e(t,i,n)}):"object"==typeof module&&module.exports?module.exports=e(t,require("./flickity"),require("fizzy-ui-utils")):e(t,t.Flickity,t.fizzyUIUtils)}(window,function(t,e,i){function n(t){var e=document.createDocumentFragment();return t.forEach(function(t){e.appendChild(t.element)}),e}var s=e.prototype;return s.insert=function(t,e){var i=this._makeCells(t);if(i&&i.length){var s=this.cells.length;e=void 0===e?s:e;var o=n(i),r=e==s;if(r)this.slider.appendChild(o);else{var a=this.cells[e].element;this.slider.insertBefore(o,a)}if(0===e)this.cells=i.concat(this.cells);else if(r)this.cells=this.cells.concat(i);else{var h=this.cells.splice(e,s-e);this.cells=this.cells.concat(i).concat(h)}this._sizeCells(i);var l=e>this.selectedIndex?0:i.length;this._cellAddedRemoved(e,l)}},s.append=function(t){this.insert(t,this.cells.length)},s.prepend=function(t){this.insert(t,0)},s.remove=function(t){var e,n,s=this.getCells(t),o=0,r=s.length;for(e=0;e=this.cells.length)){var r=this.cells.slice(n,s+1);this.navSelectedElements=r.map(function(t){return t.element}),this.changeNavSelectedClass("add")}}},n.changeNavSelectedClass=function(t){this.navSelectedElements.forEach(function(e){e.classList[t]("is-nav-selected")})},n.activateAsNavFor=function(){this.navCompanionSelect(!0)},n.removeNavSelectedElements=function(){this.navSelectedElements&&(this.changeNavSelectedClass("remove"),delete this.navSelectedElements)},n.onNavStaticClick=function(t,e,i,n){"number"==typeof n&&this.navCompanion.selectCell(n)},n.deactivateAsNavFor=function(){this.removeNavSelectedElements()},n.destroyAsNavFor=function(){this.navCompanion&&(this.navCompanion.off("select",this.onNavCompanionSelect),this.off("staticClick",this.onNavStaticClick),delete this.navCompanion)},t}),function(t,e){"use strict";"function"==typeof define&&define.amd?define("imagesloaded/imagesloaded",["ev-emitter/ev-emitter"],function(i){return e(t,i)}):"object"==typeof module&&module.exports?module.exports=e(t,require("ev-emitter")):t.imagesLoaded=e(t,t.EvEmitter)}("undefined"!=typeof window?window:this,function(t,e){function i(t,e){for(var i in e)t[i]=e[i];return t}function n(t){var e=[];if(Array.isArray(t))e=t;else if("number"==typeof t.length)for(var i=0;i -1 ) {
this.contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*');
}
break;
case 'vimeo':
if ( this.src.indexOf("vimeo.com") > -1 ) {
var player = new Vimeo.Player(this);
player.pause();
}
break;
case 'site123':
if (this.contentWindow.player) this.contentWindow.player.pause();
break;
}
});
$isotopeContainer.isotope('layout');
});
$isotopeContainer.on( 'arrangeComplete', function( event, filteredItems ) {
$flickityContainer.flickity('resize');
});
$categories.off('click').on('click',function () {
var $this = $(this);
$isotopeContainer.isotope({
filter: function() {
return gallery_Filter_Layout6($(this),$this.data('filter'));
}
});
$categories.removeClass('active');
$this.addClass('active');
$flickityContainer.flickity('resize');
return false;
});
$categories.first().trigger('click');
});
});
}
/**
* The function filter the items related to the selected category.
* We create a custom filter function because we like to filter
* the items via data-attributes and not by class.
*/
function gallery_Filter_Layout6( $item, filter ) {
return $item.attr('data-filter') == filter;
}jQuery(function($) {
GalleryModuleInitialize_Layout7();
});
/**
* The function initialize the Gallery Module.
*/
function GalleryModuleInitialize_Layout7() {
$( document ).on( 's123.page.ready', function( event ) {
/**
* Gallery & Video modules using the same classes but need to get different
* settings, so we create a selector to choose only the galley modules.
* Note: if we choose also the video the magnificPopup wont work.
*/
var $section = $('section.s123-module-gallery.layout-7:not(.s123-module-videos)');
$section.each(function( index ) {
var $sectionThis = $(this);
var $isotopeContainer = $sectionThis.find('.isotope-gallery-container');
var $categories = $sectionThis.find('.filter li');
var $flickityContainer = $sectionThis.find('.gallery-images-container');
/**
* Gallery Modules - Flickity Initial
* Documentation : http://flickity.metafizzy.co/options.html
*/
$flickityContainer.flickity({
imagesLoaded: true,
initialIndex: 1,
lazyLoad: 2
});
/**
* Gallery Modules - Isotope Initial
*/
$isotopeContainer.isotope({
itemSelector: '.gallery-images-container, .gallery-image-caption'
});
$flickityContainer.on('settle.flickity', function() {
var $this = $(this);
var flkty = Flickity.data( this );
$this.next('.gallery-image-caption').html($(flkty.selectedElement).data('caption'));
/**
* Stop Videos - We need to stop all the videos every time the
* user slide to prevent 2 videos playing at the same time.
*/
$sectionThis.find('.gallery-video-container:not(.is-selected) iframe').each(function () { // YouTube/Vimeo
switch ( $(this).data('player') ) {
case 'youtube':
if ( this.src.indexOf("youtube.com") > -1 ) {
this.contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*');
}
break;
case 'vimeo':
if ( this.src.indexOf("vimeo.com") > -1 ) {
var player = new Vimeo.Player(this);
player.pause();
}
break;
case 'site123':
if (this.contentWindow.player) this.contentWindow.player.pause();
break;
}
});
$isotopeContainer.isotope('layout');
});
$isotopeContainer.on( 'arrangeComplete', function( event, filteredItems ) {
$flickityContainer.flickity('resize');
});
$categories.off('click').on('click',function () {
var $this = $(this);
$isotopeContainer.isotope({
filter: function() {
return gallery_Filter_Layout7($(this),$this.data('filter'));
}
});
$categories.removeClass('active');
$this.addClass('active');
$flickityContainer.flickity('resize');
return false;
});
$categories.first().trigger('click');
});
});
}
/**
* The function filter the items related to the selected category.
* We create a custom filter function because we like to filter
* the items via data-attributes and not by class.
*/
function gallery_Filter_Layout7( $item, filter ) {
return $item.attr('data-filter') == filter;
}jQuery(function($) {
GalleryModuleInitialize_Layout8();
});
/**
* The function initialize the Gallery Module.
*/
function GalleryModuleInitialize_Layout8() {
$( document ).on( 's123.page.ready', function( event ) {
/**
* Gallery & Video modules using the same classes but need to get different
* settings, so we create a selector to choose only the galley modules.
* Note: if we choose also the video the magnificPopup wont work.
*/
var $section = $('section.s123-module-gallery.layout-8:not(.s123-module-videos)');
$section.each(function( index ) {
var $sectionThis = $(this);
var $categories = $sectionThis.find('.filter li');
var $images = $sectionThis.find('.gallery-image');
/**
* Gallery Modules - Magnific Popup Initial
* Documentation : http://dimsemenov.com/plugins/magnific-popup/documentation.html
*/
$sectionThis.magnificPopup({
mainClass: 'mfp-module-gallery',
delegate: '.mfp-image:visible', // Categories Filter
closeOnContentClick: true,
closeBtnInside: false,
tLoading: translations.loading, // Text that is displayed during loading
gallery: {
enabled: true,
tClose: translations.closeEsc, // Alt text on close button
tPrev: translations.previousLeftArrowKey, // Alt text on left arrow
tNext: translations.NextRightArrowKey, // Alt text on right arrow
tCounter: '%curr% '+translations.of+' %total%' // Markup for "1 of 7" counter
},
image: {
markup: '
'+
''+
''+
'
'+
''+
''+
''+
'
'+
'
',
titleSrc: 'data-caption',
tError: translations.imageCouldNotLoaded // Error message when image could not be loaded
},
iframe: {
/**
* Magnific Popup doesn't show the caption on IFrames so we add it manually
* Source: https://stackoverflow.com/a/22023434/469161
*/
markup: '
' +
'' +
'' +
'' +
'
',
patterns: {
youtube: {
index: 'youtube.com/',
id: function(url) {
var matches = url.match(/[\\?\\&]v=([^\\?\\&]+)/);
if ( !matches || !matches[1] ) return null;
return matches[1];
},
src: '//www.youtube.com/embed/%id%?autoplay=1'
},
vimeo: {
index: 'vimeo.com/',
id: function(url) {
var matches = url.match(/(https?:\/\/)?(www.)?(player.)?vimeo.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/);
if ( !matches || !matches[5] ) return null;
return matches[5];
},
src: '//player.vimeo.com/video/%id%?autoplay=1'
},
site123: {
index: $GLOBALS['cdn-user-files'],
id: function( url ) {
/**
* Mobile Handler - The auto-play is not working at mobile
* if the video is not muted, so we disable it.
*/
if ( isMobile.any() ) url += '&autoplay=0';
return url;
},
src: '/include/globalVideoPlayer.php?cad=1&url=%id%'
},
site123Processing: {
index: '/files/images/video-processing.png',
id: function( url ) {
/**
* Mobile Handler - The auto-play is not working at mobile
* if the video is not muted, so we disable it.
*/
if ( isMobile.any() ) url += '&autoplay=0';
return url;
},
src: '/include/globalVideoPlayer.php?cad=1&url=%id%'
}
}
},
callbacks: {
elementParse: function( item ) {
if( item.el.data('type') === 'video' ) {
item.type = 'iframe';
} else {
item.type = 'image';
}
},
markupParse: function(template, values, item) {
/**
* Magnific Popup doesn't show the caption on IFrames so we add it manually
* Source: https://stackoverflow.com/a/22023434/469161
*/
values.title = item.el.data('caption');
/**
* Prevent closing the pop-up when the user clicks on caption, I didn't found
* a good event to handle it for all medias (including videos) so I use timeout.
*/
setTimeout(function(){
$('.mfp-title').off('click').click(function( event ) {
event.stopPropagation();
});
},500);
if ( !this.mp_currentPageUrl ) this.mp_currentPageUrl = window.location.href;
window.history.replaceState(this.mp_currentPageUrl,'Title',item.el.data('image-page-url'));
},
updateStatus: function( data ) {
var $bar = $('.mfp-bottom-bar');
var $close = $('.mfp-caption-close');
$bar.show();
$close .off('click').on('click',function( event ) {
event.stopPropagation();
$bar.hide();
});
$bar.height() > 50 ? $close .show() : $close .hide();
},
close: function(item) {
window.history.replaceState('','Title',this.mp_currentPageUrl);
}
}
});
$categories.off('click').on('click',function ( event, initialize ) {
var $category = $(this);
$categories.removeClass('active');
$category.addClass('active');
$sectionThis.css({ minHeight: $sectionThis.height() });
var $filtered = $category.data('filter') == 's123-g-show-all' ? $images : $images.filter('[data-filter=' + $category.data('filter') + ']');
if ( initialize ) {
$images.hide();
$filtered.show();
$sectionThis.css({ minHeight: '' });
$(window).trigger('scroll');
} else {
$images.fadeOut(200).promise().done( function() {
$filtered.fadeIn(200);
$sectionThis.css({ minHeight: '' });
$(window).trigger('scroll');
});
}
return false;
});
$categories.first().trigger('click',true);
});
});
}jQuery(function($) {
AboutModuleInitialize_Layout2_4();
});
function AboutModuleInitialize_Layout2_4() {
$( document ).on( 's123.page.ready', function( event ) {
var $section = $('section.s123-module-about.layout-2,section.s123-module-about.layout-4');
$section.each(function( index ) {
var $sectionThis = $(this);
var $flickityContainer = $sectionThis.find('.carousel');
/**
* Gallery Modules - Flickity Initial
* Documentation : http://flickity.metafizzy.co/options.html
*/
$flickityContainer.flickity({
imagesLoaded: true,
lazyLoad: 2,
pageDots: false
});
});
});
}jQuery(function($) {
ContactModuleInitialize();
});
/**
* The function initialize the Contact Module.
*/
function ContactModuleInitialize() {
$( document ).on( 's123.page.ready', function( event ) {
var $section = $('section.s123-module-contact');
$section.each( function( index ) {
var $sectionThis = $(this);
if ( false ) {
buisnessHoursTemplate.init({
$buisnessHourContainer : $sectionThis.find('#businessWorkingDays'),
buisnessHourJSON : $sectionThis.find("#businessHours")
});
}
$sectionThis.find('.contactUsForm').each( function( index ) {
var $form = $(this);
/**
* jQuery Validation Plugin Initial
* Documentation : http://jqueryvalidation.org/documentation/
*/
$form.validate({
errorElement: 'div',
errorClass: 'help-block',
focusInvalid: true,
ignore: "",
highlight: function (e) {
$(e).closest('.form-group').removeClass('has-info').addClass('has-error');
},
success: function (e) {
$(e).closest('.form-group').removeClass('has-error');
$(e).remove();
},
submitHandler: function( form ) {
var $form = $(form);
var thankYouMessage = translations.ThankYouAfterSubmmit;
if ( $form.data('thanks-msg') ) {
thankYouMessage = $form.data('thanks-msg');
}
$form.find('button:submit').prop('disabled', true);
var url = "/versions/"+$('#versionNUM').val()+"/include/contactO.php";
if ( $form.hasClass('custom-form') ) {
url = "/versions/"+$('#versionNUM').val()+"/include/customFormO.php";
}
$.ajax({
type: "POST",
url: url,
data: $form.serialize(),
success: function( data ) {
var dataObj = jQuery.parseJSON(data);
$form.trigger("reset");
bootbox.alert({
title: translations.sent,
message: thankYouMessage+'',
className: 'contactUsConfirm',
backdrop: true
});
$form.find('button:submit').prop('disabled', false);
WizardNotificationUpdate();
}
});
return false;
}
});
});
});
});
}jQuery(function($) {
TeamModuleInitialize();
});
/**
* The function initialize the Team Module.
*/
function TeamModuleInitialize() {
$( document ).on( 's123.page.ready', function( event ) {
var $section = $('section.s123-module-team');
$section.each(function( index ) {
var $sectionThis = $(this);
$sectionThis.find('.team-phone-btn').click(function() {
var $this = $(this);
var $teamPhone = $this.closest('.team-phone');
buildPopup('teamPopupFloatDivPhone','',$teamPhone.find('.team-phone-popover').html(),'',true,true,true,'','');
});
categories = new ModuleLayoutCategories({
$items : $sectionThis.find('.team-category'),
$categoriesContainer : $sectionThis.find('.categories-panel'),
$filterButton : $sectionThis.find('.items-responsive-filter'),
$categories : $sectionThis.find('.items-categories-container li')
});
});
});
}jQuery(function($) {
CustomFormModuleInitialize();
});
/**
* The function initialize the Custom Form Module.
*/
function CustomFormModuleInitialize() {
$( document ).on( 's123.page.ready', function( event ) {
var $section = $('section.s123-module-custom-form-builder');
$section.each( function( index ) {
var $sectionThis = $(this);
$sectionThis.find('.customForm').each( function( index ) {
var $form = $(this);
/**
* jQuery Validation Plugin Initial
* Documentation : http://jqueryvalidation.org/documentation/
*/
$form.validate({
errorElement: 'div',
errorClass: 'help-block',
focusInvalid: true,
ignore: "",
highlight: function (e) {
$(e).closest('.form-group').removeClass('has-info').addClass('has-error');
},
success: function (e) {
$(e).closest('.form-group').removeClass('has-error');
$(e).remove();
},
submitHandler: function( form ) {
var $form = $(form);
$form.find('button:submit').prop('disabled', true);
var sendingDialog = bootbox.alert({
title: translations.sending,
message: '
'+translations.loading+'
',
className: 'contactUsConfirm',
backdrop: true
});
$.ajax({
type: "POST",
url: "/versions/"+$('#versionNUM').val()+"/include/customFormO.php",
data: new FormData($form.get(0)),
cache: false,
contentType: false,
processData: false,
success: function( data ) {
var dataObj = jQuery.parseJSON(data);
$form.trigger("reset");
message = ''+translations.ThankYouAfterSubmmit+'';
var $sentMessage = $(message);
sendingDialog.find('.modal-title').html(translations.sent);
sendingDialog.find('.bootbox-body').append($sentMessage.hide());
$('#customFormLoadingMessage').hide();
$sentMessage.slideDown(200);
$form.find('button:submit').prop('disabled', false);
WizardNotificationUpdate();
}
});
return false;
}
});
});
});
});
}jQuery(function($) {
MenuModuleInitialize();
});
/**
* The function initialize the Menu Module.
*/
function MenuModuleInitialize() {
$( document ).on( "s123.page.load", function( event ) {
var $sections = $('.s123-module-menu.layout-2');
$sections.each(function( index ) {
var $s = $(this);
var $categories = $s.find('.filter a');
$categories.off('click').on('click',function ( event, initialize ) {
var $category = $(this);
var $products = $s.find('.menu-category');
$s.find('.filter li').removeClass('active');
$category.parent().addClass('active');
var $filtered = $products.filter('[data-filter=' + $category.data('filter') + ']')
if ( initialize ) {
$products.hide();
$filtered.show();
} else {
$products.fadeOut(200).promise().done( function() {
$filtered.fadeIn(200);
$(window).trigger('scroll');
});
}
return false;
});
$categories.first().trigger('click',true);
});
});
}/**
* Module Layout Categories plugin.
*/
function ModuleLayoutCategories( settings ) {
var MC = this;
/**
* Add categories click event
*/
MC.addClickEvent = function() {
MC.$categories.off('click').on('click',function ( event, initialize ) {
var $category = $(this);
MC.$categories.removeClass('active');
$category.addClass('active');
var $filtered = MC.$items.filter('[data-categories-filter=' + $category.data('categories-filter') + ']');
if ( initialize ) {
MC.$items.hide();
$filtered.show();
} else {
MC.$items.fadeOut(200).promise().done( function() {
$filtered.fadeIn(200);
$(window).trigger('scroll');
});
}
return false;
});
}
/**
* Add mobile responsive filter click event
*/
MC.addFilterButton = function() {
MC.$filterButton.off('click').on('click', function() {
var $category = $(this);
MC.$categoriesContainer.slideToggle('slow');
$category.toggleClass('active');
return false;
});
}
if ( settings.length === 0 ) return;
MC.$categories = settings.$categories;
MC.$items = settings.$items;
MC.$filterButton = settings.$filterButton;
MC.$categoriesContainer = settings.$categoriesContainer;
MC.addClickEvent();
MC.$categories.first().trigger('click',true);
if ( MC.$filterButton ) MC.addFilterButton();
};// Run when the page ready (before images and other resource)
jQuery(function($) {
var rtl = $('html[dir=rtl]').length === 1;
var $section = $('section.s123-page-data-products');
var $mainImage = $section.find('.main-image > div');
var $productOwlcarousel = $section.find('#productOwlcarousel');
if ( $section.length === 0 ) return;
jQueryZoomInitialize($mainImage);
/**
* Owl Carousel 2 Initialize
* Documentation: http://www.owlcarousel.owlgraphic.com/docs/api-options.html
*/
$productOwlcarousel.owlCarousel({
autoPlay: false,
items : 4,
margin: 10,
stagePadding: 5,
startPosition: 0,
loop: false,
center: false,
nav: true,
rtl: rtl,
navText: [
'',
''
],
dots: true
});
$productOwlcarousel.find('.item').click(function() {
var $clickedImage = $(this).find('.item-image');
var videoPath = '';
if ($clickedImage.data('media-type') == 'video') {
videoPath = $clickedImage.data('video-path');
}
jQueryZoomInitialize($clickedImage);
$mainImage.css({
backgroundImage: $clickedImage.css('background-image')
});
});
/**
* The function initialize the jQuery Zoom Plugin on the main product image.
* Documentation: http://www.jacklmoore.com/zoom/
*
* @param {string} url - The URL of the image we like to zoom in to it.
*/
function jQueryZoomInitialize( $clickedImage ) {
if ( !$mainImage || $mainImage.length === 0 ) return;
if ( !$clickedImage || $clickedImage.length === 0 ) return;
if ($clickedImage.data('media-type') == 'video' ) {
$mainImage.empty();
$('').appendTo($mainImage);
} else {
$mainImage.empty();
var url = $clickedImage.data('zoom-image');
if ( isMobile.any() ) return;
$mainImage.trigger('zoom.destroy');
/**
* It take some time for the zoom image to loaded and if the user hover the image
* before the zoom image finished loaded the zoom is not activate. We fix it by
* creating a div and removing it (for activate the `'mouseover' event).
*/
var loading = $('').appendTo($mainImage);
$mainImage.zoom({
url: url,
magnify: 1,
touch: true,
callback: function() {
loading.remove();
},
});
}
}
(function () {
var $productOptions = $section.find(".product-options");
var $options = $productOptions.find('.p-o-container');
if ( $productOptions.length !== 0 ) {
$options.filter('[data-type="color"]').each( function() {
var $option = $(this);
var $colors = $option.find('.p-o-color');
$colors.click( function( event ) {
var $color = $(this);
$colors.filter('.selected').removeClass('selected');
$color.addClass('selected');
$option.find('.p-o-item-value').html(fixQuotIssue($color.attr('title')));
update();
});
$colors.first().trigger('click'); // default value
});
$options.filter('[data-type="list"]').each( function() {
var $option = $(this);
var $list = $option.find('.p-o-list');
$list.change( function( event ) {
$option.find('.p-o-item-value').html(fixQuotIssue($list.val()));
update();
}).trigger('change'); // default value
});
update();
}
/**
* The function update the product options object.
*/
function update() {
var po = [];
var totalItemsPrice = 0.00;
$options.each( function() {
var $option = $(this);
var pOption = new ProductOptions();
pOption.id = $option.get(0).id;
pOption.title = fixQuotIssue($option.data('title'));
pOption.type = $option.data('type');
switch( $option.data('type') ) {
case 'color':
var $color = $option.find('.p-o-color.selected');
if ( $color.length === 0 ) return;
pOption.item.id = $color.get(0).id
pOption.item.title = fixQuotIssue($color.attr('title'));
pOption.item.price = $color.data('price');
break;
case 'list':
var $list = $option.find('.p-o-list');
var $listSelectedOpt = $list.find('option:selected');
if ( $list.find('option').length === 0 ) return;
pOption.item.id = $listSelectedOpt.get(0).id;
pOption.item.title = fixQuotIssue($list.val());
pOption.item.price = $listSelectedOpt.data('price');
break;
}
totalItemsPrice += parseFloat(pOption.item.price);
po.push(pOption);
});
$('#productOptions').html(JSON.stringify(po));
addItemsPrice(totalItemsPrice);
}
/**
* Product Option Class.
*/
function ProductOptions() {
return {
id: null,
title: null,
type: null,
item: {
id: null,
title: null,
price: 0
}
};
}
/**
* The function add product items price to the product price.
*
* @param {float} totalItemsPrice - The total items price.
*/
function addItemsPrice( totalItemsPrice ) {
var $productPrice = $section.find('#productPrice');
var $price = $productPrice.find('[data-type="price"]');
if ( !$.isNumeric(totalItemsPrice) ) return;
if ( parseFloat($productPrice.data('price'))
+ parseFloat(totalItemsPrice) == parseFloat($price.html()) ) return;
var p = parseFloat($productPrice.data('price')) + parseFloat(totalItemsPrice);
$price.html(p.toFixed(2));
}
})();
(function () {
var $ct = $section.find("#product-custom-text");
var $ct_fieldTitle = $ct.find("#ct_fieldTitle");
var $ct_charLimit = $ct.find("#ct_charLimit");
var $orderButtonPopup = $section.find(".orderButtonPopup");
$ct_fieldTitle.on('input', function( event ) {
var max = $ct.data('char-limit');
var length = $ct_fieldTitle.val().length
if ( length > max) {
$ct_fieldTitle.val($ct_fieldTitle.val().substring(0, max));
} else {
$ct_charLimit.html(max - length);
}
});
$ct_fieldTitle.blur( function( event ) {
update();
});
$orderButtonPopup.click( function( event ) {
update();
});
/**
* The function update the custom text object.
*/
function update() {
var ct = new CustomText();
ct.fieldTitle = fixQuotIssue($ct.data('field-title'));
ct.value = $ct_fieldTitle.val();
$('#customText').html(JSON.stringify(ct));
}
/**
* Custom Text Class.
*/
function CustomText() {
return {
fieldTitle: null,
value: null
};
}
})();
/**
* The function convert `"` to `"`, We use data attribute to to pass
* some of the fields with `htmlspecialchars()` on the server side to
* prevent HTML break with quot, the JS function `stringify` doesn't
* handle `"` chars so we fix it manually by replacing it to `"`.
* In the feature we need to stop passing the values using `data`.
*/
function fixQuotIssue( value ) {
if ( !value ) return value;
return value.toString().replace(/\"/g,'\"');
}
$('.quantity_field').on('input', function() {
var $this = $(this);
if ( $this.val().length > 0 && !$.isNumeric($this.val()) ) $this.val(1);
if ( !$.isNumeric($this.val()) ) $this.val($this.val().replace(/[^0-9]/g,''));
if ( $.isNumeric($this.val()) && $this.val() <= 0 ) $this.val(1);
if ( parseInt($this.val()) > parseInt($this.prop('max')) ) {
$this.val($this.prop('max'));
quantityPopover($this,translations.productQuntityLimit.replace('{{units_limitation}}',$this.prop('max')));
} else if ( parseInt($this.val()) < parseInt($this.prop('min')) ) {
$this.val($this.prop('min'));
quantityPopover($this,translations.productQuntityLimitMin.replace('{{units_limitation}}',$this.prop('min')));
}
$section.find('.btn-buy-now.orderButtonPopup').data('quantity-amount',$this.val());
});
/**
* The function show a popover with a message related to the quantity validations.
*/
function quantityPopover( $input, message ) {
$input.popover({
container: $section,
content: message,
trigger: 'manual',
template: '
',
placement: function(popover, input) {
return isMobile.any() ? 'auto' : 'bottom';
}
});
$input.popover('show');
clearTimeout($input.data('q-p-timeout'));
$input.data('q-p-timeout',setTimeout(function(){
$input.popover('destroy');
},3000));
}
/**
* The function update the quantity
*/
function updateQuantity( $input, operator ) {
/**
* When product is out of stock we need to ignore the click events by checking
* if the `quantity-container` has a data attribute.
*/
if ( $input.closest('.quantity-container').data('disabled') == '1' ) return;
var quantity = parseInt($input.val());
var maxQuantity = parseInt($input.attr('max'));
var minQuantity = parseInt($input.attr('min'));
if ( operator === 'plus' && (quantity + 1) > maxQuantity ) {
quantityPopover($input,translations.productQuntityLimit.replace('{{units_limitation}}',$input.prop('max')));
} else if ( operator === 'minus' && quantity !== 1 && (quantity - 1) < minQuantity ) {
quantityPopover($input,translations.productQuntityLimitMin.replace('{{units_limitation}}',$input.prop('min')));
}
if ( operator === 'minus' && quantity > minQuantity ) quantity = quantity - 1;
if ( operator === 'plus' && quantity < maxQuantity ) quantity = quantity + 1;
if ( !$.isNumeric(quantity) ) quantity = 1;
$section.find('.btn-buy-now.orderButtonPopup').data('quantity-amount',quantity);
$input.val(quantity);
}
$section.find('.quantity-plus-btn').off('click').on('click', function() {
updateQuantity($(this).closest('.quantity-container').find('.quantity_field'),'plus');
});
$section.find('.quantity-minus-btn').off('click').on('click', function() {
updateQuantity($(this).closest('.quantity-container').find('.quantity_field'),'minus');
});
});jQuery(function($) {
AutoSetProductsImage();
});
function AutoSetProductsImage() {
$( document ).on( "s123.page.load", function( event ) {
$('.s123-module-products').each(function() {
var $thisModule = $(this);
$thisModule.find('.product-image.autoFitByHeight').first().each(function() {
var $this = $(this);
AutoSetProductsImage_onImageReady($this.find('img'),AutoSetProductsImage_autoFitByHeight,$this,$thisModule);
});
$thisModule.find('.product-image.autoFitByWidth').first().each(function() {
var $this = $(this);
AutoSetProductsImage_onImageReady($this.find('img'),AutoSetProductsImage_autoFitByWidth,$this,$thisModule);
});
});
var $box = $('.s123-page-data .product-container .product-images .main-image, .s123-module .product-container .product-images .main-image');
if ( $box.length>0 ) {
if ( $box.closest('.s123-module-eCommerce').length !== 0 ) return;
AutoSetProductsImage_onImageReady($('.product-container .main-image .hideImageRatio'),AutoSetProductsImage_autoFitProductPage,$box,'');
}
});
}
function AutoSetProductsImage_autoFitByHeight($imgBox,$thisModule) {
var width = $imgBox.find('img').width();
var height = $imgBox.find('img').height();
var boxMagic_ratio = width/height;
var boxWidth = $imgBox.width();
$thisModule.find('.product-image.autoFitByHeight').height(boxWidth/boxMagic_ratio);
}
function AutoSetProductsImage_autoFitByWidth($imgBox,$thisModule) {
var width = $imgBox.find('img').width();
var height = $imgBox.find('img').height();
var boxMagic_ratio = width/height;
var boxHeight = $imgBox.height();
$thisModule.find('.product-image.autoFitByWidth').width(boxHeight*boxMagic_ratio);
}
function AutoSetProductsImage_autoFitProductPage($imgBox,$thisModule) {
var boxWidth = $imgBox.width();
var imgWidth = $('.product-container .main-image .hideImageRatio').width();
var imgHeight = $('.product-container .main-image .hideImageRatio').height();
var ratio = imgWidth/imgHeight;
if (boxWidth>imgWidth) {
boxWidth = imgWidth;
$imgBox.width(boxWidth);
}
$imgBox.height(boxWidth/ratio);
}
function AutoSetProductsImage_onImageReady(selector, handler, $imgBox, $thisModule) {
var list;
list = typeof selector === 'string' ? $(selector) : selector;
list.each(function(index, element) {
if (element.complete) {
setTimeout(function() {
fireHandler.call(element);
}, 0); // Won't really be 0, but close
}
else {
$(element).bind('load', fireHandler);
}
});
function fireHandler(event) {
$(this).unbind('load', fireHandler);
handler.call(this,$imgBox,$thisModule);
}
}jQuery(function($) {
ProductsModuleInitialize();
});
/**
* The function initialize the Products Module.
*/
function ProductsModuleInitialize() {
$( document ).on( "s123.page.load", function( event ) {
var $sections = $('.s123-module-products.layout-2');
$sections.each(function( index ) {
var $s = $(this);
categories = new ModuleLayoutCategories({
$items : $s.find('.products-category'),
$categoriesContainer : $s.find('.categories-panel'),
$filterButton : $s.find('.items-responsive-filter'),
$categories : $s.find('.items-categories-container li')
});
});
});
}jQuery(function($) {
ProductsModuleInitialize_Layout3();
});
/**
* The function initialize the Products Module.
*/
function ProductsModuleInitialize_Layout3() {
$( document ).on( "s123.page.ready", function( event ) {
var $sections = $('.s123-module-products.layout-3');
$sections.each(function( index ) {
var $s = $(this);
categories = new ModuleLayoutCategories({
$items : $s.find('.products-container > div'),
$categoriesContainer : $s.find('.categories-panel'),
$filterButton : $s.find('.items-responsive-filter'),
$categories : $s.find('.items-categories-container li')
});
});
});
}jQuery(function($) {
TimelineModuleInitialize();
});
/**
* The function initialize the Timeline Module.
*/
function TimelineModuleInitialize() {
$( document ).on( 's123.page.ready', function( event ) {
var timelineBlocks = $('.cd-timeline-block'),
offset = 0.8;
hideBlocks(timelineBlocks, offset);
$(window).on('scroll', function(){
(!window.requestAnimationFrame)
? setTimeout(function(){ showBlocks(timelineBlocks, offset); }, 100)
: window.requestAnimationFrame(function(){ showBlocks(timelineBlocks, offset); });
});
function hideBlocks(blocks, offset) {
blocks.each(function(){
( $(this).offset().top > $(window).scrollTop()+$(window).height()*offset ) && $(this).find('.cd-timeline-img, .cd-timeline-content').addClass('is-hidden');
});
}
function showBlocks(blocks, offset) {
blocks.each(function(){
( $(this).offset().top <= $(window).scrollTop()+$(window).height()*offset && $(this).find('.cd-timeline-img').hasClass('is-hidden') ) && $(this).find('.cd-timeline-img, .cd-timeline-content').removeClass('is-hidden').addClass('bounce-in');
});
}
});
}/*! flipclock 2015-01-19 */
var Base=function(){};Base.extend=function(a,b){"use strict";var c=Base.prototype.extend;Base._prototyping=!0;var d=new this;c.call(d,a),d.base=function(){},delete Base._prototyping;var e=d.constructor,f=d.constructor=function(){if(!Base._prototyping)if(this._constructing||this.constructor==f)this._constructing=!0,e.apply(this,arguments),delete this._constructing;else if(null!==arguments[0])return(arguments[0].extend||c).call(arguments[0],d)};return f.ancestor=this,f.extend=this.extend,f.forEach=this.forEach,f.implement=this.implement,f.prototype=d,f.toString=this.toString,f.valueOf=function(a){return"object"==a?f:e.valueOf()},c.call(f,b),"function"==typeof f.init&&f.init(),f},Base.prototype={extend:function(a,b){if(arguments.length>1){var c=this[a];if(c&&"function"==typeof b&&(!c.valueOf||c.valueOf()!=b.valueOf())&&/\bbase\b/.test(b)){var d=b.valueOf();b=function(){var a=this.base||Base.prototype.base;this.base=c;var b=d.apply(this,arguments);return this.base=a,b},b.valueOf=function(a){return"object"==a?b:d},b.toString=Base.toString}this[a]=b}else if(a){var e=Base.prototype.extend;Base._prototyping||"function"==typeof this||(e=this.extend||e);for(var f={toSource:null},g=["constructor","toString","valueOf"],h=Base._prototyping?0:1;i=g[h++];)a[i]!=f[i]&&e.call(this,i,a[i]);for(var i in a)f[i]||e.call(this,i,a[i])}return this}},Base=Base.extend({constructor:function(){this.extend(arguments[0])}},{ancestor:Object,version:"1.1",forEach:function(a,b,c){for(var d in a)void 0===this.prototype[d]&&b.call(c,a[d],d,a)},implement:function(){for(var a=0;a',''].join("");d&&(e=""),b=this.factory.localize(b);var f=['',''+(b?b:"")+"",e,""],g=a(f.join(""));return this.dividers.push(g),g},createList:function(a,b){"object"==typeof a&&(b=a,a=0);var c=new FlipClock.List(this.factory,a,b);return this.lists.push(c),c},reset:function(){this.factory.time=new FlipClock.Time(this.factory,this.factory.original?Math.round(this.factory.original):0,{minimumDigits:this.factory.minimumDigits}),this.flip(this.factory.original,!1)},appendDigitToClock:function(a){a.$el.append(!1)},addDigit:function(a){var b=this.createList(a,{classes:{active:this.factory.classes.active,before:this.factory.classes.before,flip:this.factory.classes.flip}});this.appendDigitToClock(b)},start:function(){},stop:function(){},autoIncrement:function(){this.factory.countdown?this.decrement():this.increment()},increment:function(){this.factory.time.addSecond()},decrement:function(){0==this.factory.time.getTimeSeconds()?this.factory.stop():this.factory.time.subSecond()},flip:function(b,c){var d=this;a.each(b,function(a,b){var e=d.lists[a];e?(c||b==e.digit||e.play(),e.select(b)):d.addDigit(b)})}})}(jQuery),function(a){"use strict";FlipClock.Factory=FlipClock.Base.extend({animationRate:1e3,autoStart:!0,callbacks:{destroy:!1,create:!1,init:!1,interval:!1,start:!1,stop:!1,reset:!1},classes:{active:"flip-clock-active",before:"flip-clock-before",divider:"flip-clock-divider",dot:"flip-clock-dot",label:"flip-clock-label",flip:"flip",play:"play",wrapper:"flip-clock-wrapper"},clockFace:"HourlyCounter",countdown:!1,defaultClockFace:"HourlyCounter",defaultLanguage:"english",$el:!1,face:!0,lang:!1,language:"english",minimumDigits:0,original:!1,running:!1,time:!1,timer:!1,$wrapper:!1,constructor:function(b,c,d){d||(d={}),this.lists=[],this.running=!1,this.base(d),this.$el=a(b).addClass(this.classes.wrapper),this.$wrapper=this.$el,this.original=c instanceof Date?c:c?Math.round(c):0,this.time=new FlipClock.Time(this,this.original,{minimumDigits:this.minimumDigits,animationRate:this.animationRate}),this.timer=new FlipClock.Timer(this,d),this.loadLanguage(this.language),this.loadClockFace(this.clockFace,d),this.autoStart&&this.start()},loadClockFace:function(a,b){var c,d="Face",e=!1;return a=a.ucfirst()+d,this.face.stop&&(this.stop(),e=!0),this.$el.html(""),this.time.minimumDigits=this.minimumDigits,c=FlipClock[a]?new FlipClock[a](this,b):new FlipClock[this.defaultClockFace+d](this,b),c.build(),this.face=c,e&&this.start(),this.face},loadLanguage:function(a){var b;return b=FlipClock.Lang[a.ucfirst()]?FlipClock.Lang[a.ucfirst()]:FlipClock.Lang[a]?FlipClock.Lang[a]:FlipClock.Lang[this.defaultLanguage],this.lang=b},localize:function(a,b){var c=this.lang;if(!a)return null;var d=a.toLowerCase();return"object"==typeof b&&(c=b),c&&c[d]?c[d]:a},start:function(a){var b=this;b.running||b.countdown&&!(b.countdown&&b.time.time>0)?b.log("Trying to start timer when countdown already at 0"):(b.face.start(b.time),b.timer.start(function(){b.flip(),"function"==typeof a&&a()}))},stop:function(a){this.face.stop(),this.timer.stop(a);for(var b in this.lists)this.lists.hasOwnProperty(b)&&this.lists[b].stop()},reset:function(a){this.timer.reset(a),this.face.reset()},setTime:function(a){this.time.time=a,this.flip(!0)},getTime:function(){return this.time},setCountdown:function(a){var b=this.running;this.countdown=a?!0:!1,b&&(this.stop(),this.start())},flip:function(a){this.face.flip(!1,a)}})}(jQuery),function(a){"use strict";FlipClock.List=FlipClock.Base.extend({digit:0,classes:{active:"flip-clock-active",before:"flip-clock-before",flip:"flip"},factory:!1,$el:!1,$obj:!1,items:[],lastDigit:0,constructor:function(a,b){this.factory=a,this.digit=b,this.lastDigit=b,this.$el=this.createList(),this.$obj=this.$el,b>0&&this.select(b),this.factory.$el.append(this.$el)},select:function(a){if("undefined"==typeof a?a=this.digit:this.digit=a,this.digit!=this.lastDigit){var b=this.$el.find("."+this.classes.before).removeClass(this.classes.before);this.$el.find("."+this.classes.active).removeClass(this.classes.active).addClass(this.classes.before),this.appendListItem(this.classes.active,this.digit),b.remove(),this.lastDigit=this.digit}},play:function(){this.$el.addClass(this.factory.classes.play)},stop:function(){var a=this;setTimeout(function(){a.$el.removeClass(a.factory.classes.play)},this.factory.timer.interval)},createListItem:function(a,b){return['
").addClass(c.dotsClass).appendTo(this.$element)).addClass("disabled"),this._controls.$absolute.on("click","div",a.proxy(function(b){var d=a(b.target).parent().is(this._controls.$absolute)?a(b.target).index():a(b.target).parent().index();b.preventDefault(),this.to(d,c.dotsSpeed)},this));for(b in this._overrides)this._core[b]=a.proxy(this[b],this)},e.prototype.destroy=function(){var a,b,c,d;for(a in this._handlers)this.$element.off(a,this._handlers[a]);for(b in this._controls)this._controls[b].remove();for(d in this.overides)this._core[d]=this._overrides[d];for(c in Object.getOwnPropertyNames(this))"function"!=typeof this[c]&&(this[c]=null)},e.prototype.update=function(){var a,b,c,d=this._core.clones().length/2,e=d+this._core.items().length,f=this._core.maximum(!0),g=this._core.settings,h=g.center||g.autoWidth||g.dotsData?1:g.dotsEach||g.items;if("page"!==g.slideBy&&(g.slideBy=Math.min(g.slideBy,g.items)),g.dots||"page"==g.slideBy)for(this._pages=[],a=d,b=0,c=0;e>a;a++){if(b>=h||0===b){if(this._pages.push({start:Math.min(f,a-d),end:a-d+h-1}),Math.min(f,a-d)===f)break;b=0,++c}b+=this._core.mergers(this._core.relative(a))}},e.prototype.draw=function(){var b,c=this._core.settings,d=this._core.items().length<=c.items,e=this._core.relative(this._core.current()),f=c.loop||c.rewind;this._controls.$relative.toggleClass("disabled",!c.nav||d),c.nav&&(this._controls.$previous.toggleClass("disabled",!f&&e<=this._core.minimum(!0)),this._controls.$next.toggleClass("disabled",!f&&e>=this._core.maximum(!0))),this._controls.$absolute.toggleClass("disabled",!c.dots||d),c.dots&&(b=this._pages.length-this._controls.$absolute.children().length,c.dotsData&&0!==b?this._controls.$absolute.html(this._templates.join("")):b>0?this._controls.$absolute.append(new Array(b+1).join(this._templates[0])):0>b&&this._controls.$absolute.children().slice(b).remove(),this._controls.$absolute.find(".active").removeClass("active"),this._controls.$absolute.children().eq(a.inArray(this.current(),this._pages)).addClass("active"))},e.prototype.onTrigger=function(b){var c=this._core.settings;b.page={index:a.inArray(this.current(),this._pages),count:this._pages.length,size:c&&(c.center||c.autoWidth||c.dotsData?1:c.dotsEach||c.items)}},e.prototype.current=function(){var b=this._core.relative(this._core.current());return a.grep(this._pages,a.proxy(function(a,c){return a.start<=b&&a.end>=b},this)).pop()},e.prototype.getPosition=function(b){var c,d,e=this._core.settings;return"page"==e.slideBy?(c=a.inArray(this.current(),this._pages),d=this._pages.length,b?++c:--c,c=this._pages[(c%d+d)%d].start):(c=this._core.relative(this._core.current()),d=this._core.items().length,b?c+=e.slideBy:c-=e.slideBy),c},e.prototype.next=function(b){a.proxy(this._overrides.to,this._core)(this.getPosition(!0),b)},e.prototype.prev=function(b){a.proxy(this._overrides.to,this._core)(this.getPosition(!1),b)},e.prototype.to=function(b,c,d){var e;d?a.proxy(this._overrides.to,this._core)(b,c):(e=this._pages.length,a.proxy(this._overrides.to,this._core)(this._pages[(b%e+e)%e].start,c))},a.fn.owlCarousel.Constructor.Plugins.Navigation=e}(window.Zepto||window.jQuery,window,document),function(a,b,c,d){"use strict";var e=function(c){this._core=c,this._hashes={},this.$element=this._core.$element,this._handlers={"initialized.owl.carousel":a.proxy(function(c){c.namespace&&"URLHash"===this._core.settings.startPosition&&a(b).trigger("hashchange.owl.navigation")},this),"prepared.owl.carousel":a.proxy(function(b){if(b.namespace){var c=a(b.content).find("[data-hash]").andSelf("[data-hash]").attr("data-hash");if(!c)return;this._hashes[c]=b.content}},this),"changed.owl.carousel":a.proxy(function(c){if(c.namespace&&"position"===c.property.name){var d=this._core.items(this._core.relative(this._core.current())),e=a.map(this._hashes,function(a,b){return a===d?b:null}).join();if(!e||b.location.hash.slice(1)===e)return;b.location.hash=e}},this)},this._core.options=a.extend({},e.Defaults,this._core.options),this.$element.on(this._handlers),a(b).on("hashchange.owl.navigation",a.proxy(function(a){var c=b.location.hash.substring(1),e=this._core.$stage.children(),f=this._hashes[c]&&e.index(this._hashes[c]);f!==d&&f!==this._core.current()&&this._core.to(this._core.relative(f),!1,!0)},this))};e.Defaults={URLhashListener:!1},e.prototype.destroy=function(){var c,d;a(b).off("hashchange.owl.navigation");for(c in this._handlers)this._core.$element.off(c,this._handlers[c]);for(d in Object.getOwnPropertyNames(this))"function"!=typeof this[d]&&(this[d]=null)},a.fn.owlCarousel.Constructor.Plugins.Hash=e}(window.Zepto||window.jQuery,window,document),function(a,b,c,d){function e(b,c){var e=!1,f=b.charAt(0).toUpperCase()+b.slice(1);return a.each((b+" "+h.join(f+" ")+f).split(" "),function(a,b){return g[b]!==d?(e=c?b:!0,!1):void 0}),e}function f(a){return e(a,!0)}var g=a("").get(0).style,h="Webkit Moz O ms".split(" "),i={transition:{end:{WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd",transition:"transitionend"}},animation:{end:{WebkitAnimation:"webkitAnimationEnd",MozAnimation:"animationend",OAnimation:"oAnimationEnd",animation:"animationend"}}},j={csstransforms:function(){return!!e("transform")},csstransforms3d:function(){return!!e("perspective")},csstransitions:function(){return!!e("transition")},cssanimations:function(){return!!e("animation")}};j.csstransitions()&&(a.support.transition=new String(f("transition")),a.support.transition.end=i.transition.end[a.support.transition]),j.cssanimations()&&(a.support.animation=new String(f("animation")),a.support.animation.end=i.animation.end[a.support.animation]),j.csstransforms()&&(a.support.transform=new String(f("transform")),a.support.transform3d=j.csstransforms3d())}(window.Zepto||window.jQuery,window,document);(function(b){b.gritter={};b.gritter.options={position:"",class_name:"",fade_in_speed:"medium",fade_out_speed:1000,time:6000};b.gritter.add=function(f){try{return a.add(f||{})}catch(d){var c="Gritter Error: "+d;(typeof(console)!="undefined"&&console.error)?console.error(c,f):alert(c)}};b.gritter.remove=function(d,c){a.removeSpecific(d,c||{})};b.gritter.removeAll=function(c){a.stop(c||{})};var a={position:"",fade_in_speed:"",fade_out_speed:"",time:"",_custom_timer:0,_item_count:0,_is_setup:0,_tpl_close:'Close Notification',_tpl_title:'[[title]]',_tpl_item:'
[[close]][[image]]
[[title]]
[[text]]
',_tpl_wrap:'',add:function(g){if(typeof(g)=="string"){g={text:g}}if(g.text===null){throw'You must supply "text" parameter.'}if(!this._is_setup){this._runSetup()}var k=g.title,n=g.text,e=g.image||"",l=g.sticky||false,m=g.class_name||b.gritter.options.class_name,j=b.gritter.options.position,d=g.time||"";this._verifyWrapper();this._item_count++;var f=this._item_count,i=this._tpl_item;b(["before_open","after_open","before_close","after_close"]).each(function(p,q){a["_"+q+"_"+f]=(b.isFunction(g[q]))?g[q]:function(){}});this._custom_timer=0;if(d){this._custom_timer=d}var c=(e!="")?'':"",h=(e!="")?"gritter-with-image":"gritter-without-image";if(k){k=this._str_replace("[[title]]",k,this._tpl_title)}else{k=""}i=this._str_replace(["[[title]]","[[text]]","[[close]]","[[image]]","[[number]]","[[class_name]]","[[item_class]]"],[k,n,this._tpl_close,c,this._item_count,h,m],i);if(this["_before_open_"+f]()===false){return false}b("#gritter-notice-wrapper").addClass(j).append(i);var o=b("#gritter-item-"+this._item_count);o.fadeIn(this.fade_in_speed,function(){a["_after_open_"+f](b(this))});if(!l){this._setFadeTimer(o,f)}b(o).bind("mouseenter mouseleave",function(p){if(p.type=="mouseenter"){if(!l){a._restoreItemIfFading(b(this),f)}}else{if(!l){a._setFadeTimer(b(this),f)}}a._hoverState(b(this),p.type)});b(o).find(".gritter-close").click(function(){a.removeSpecific(f,{},null,true);return false;});return f},_countRemoveWrapper:function(c,d,f){d.remove();this["_after_close_"+c](d,f);if(b(".gritter-item-wrapper").length==0){b("#gritter-notice-wrapper").remove()}},_fade:function(g,d,j,f){var j=j||{},i=(typeof(j.fade)!="undefined")?j.fade:true,c=j.speed||this.fade_out_speed,h=f;this["_before_close_"+d](g,h);if(f){g.unbind("mouseenter mouseleave")}if(i){g.animate({opacity:0},c,function(){g.animate({height:0},300,function(){a._countRemoveWrapper(d,g,h)})})}else{this._countRemoveWrapper(d,g)}},_hoverState:function(d,c){if(c=="mouseenter"){d.addClass("hover");d.find(".gritter-close").show()}else{d.removeClass("hover");d.find(".gritter-close").hide()}},removeSpecific:function(c,g,f,d){if(!f){var f=b("#gritter-item-"+c)}this._fade(f,c,g||{},d)},_restoreItemIfFading:function(d,c){clearTimeout(this["_int_id_"+c]);d.stop().css({opacity:"",height:""})},_runSetup:function(){for(opt in b.gritter.options){this[opt]=b.gritter.options[opt]}this._is_setup=1},_setFadeTimer:function(f,d){var c=(this._custom_timer)?this._custom_timer:this.time;this["_int_id_"+d]=setTimeout(function(){a._fade(f,d)},c)},stop:function(e){var c=(b.isFunction(e.before_close))?e.before_close:function(){};var f=(b.isFunction(e.after_close))?e.after_close:function(){};var d=b("#gritter-notice-wrapper");c(d);d.fadeOut(function(){b(this).remove();f()})},_str_replace:function(v,e,o,n){var k=0,h=0,t="",m="",g=0,q=0,l=[].concat(v),c=[].concat(e),u=o,d=c instanceof Array,p=u instanceof Array;u=[].concat(u);if(n){this.window[n]=0}for(k=0,g=u.length;k'), // $({}) would be preferred, but there is an issue with jQuery 1.4.2
settings,
interfaceHeight,
interfaceWidth,
loadedHeight,
loadedWidth,
index,
photo,
open,
active,
closing,
loadingTimer,
publicMethod,
div = "div",
requests = 0,
previousCSS = {},
init;
function $tag(tag, id, css) {
var element = document.createElement(tag);
if (id) {
element.id = prefix + id;
}
if (css) {
element.style.cssText = css;
}
return $(element);
}
function winheight() {
return window.innerHeight ? window.innerHeight : $(window).height();
}
function Settings(element, options) {
if (options !== Object(options)) {
options = {};
}
this.cache = {};
this.el = element;
this.value = function(key) {
var dataAttr;
if (this.cache[key] === undefined) {
dataAttr = $(this.el).attr('data-cbox-'+key);
if (dataAttr !== undefined) {
this.cache[key] = dataAttr;
} else if (options[key] !== undefined) {
this.cache[key] = options[key];
} else if (defaults[key] !== undefined) {
this.cache[key] = defaults[key];
}
}
return this.cache[key];
};
this.get = function(key) {
var value = this.value(key);
return $.isFunction(value) ? value.call(this.el, this) : value;
};
}
function getIndex(increment) {
var
max = $related.length,
newIndex = (index + increment) % max;
return (newIndex < 0) ? max + newIndex : newIndex;
}
function setSize(size, dimension) {
return Math.round((/%/.test(size) ? ((dimension === 'x' ? $window.width() : winheight()) / 100) : 1) * parseInt(size, 10));
}
function isImage(settings, url) {
return settings.get('photo') || settings.get('photoRegex').test(url);
}
function retinaUrl(settings, url) {
return settings.get('retinaUrl') && window.devicePixelRatio > 1 ? url.replace(settings.get('photoRegex'), settings.get('retinaSuffix')) : url;
}
function trapFocus(e) {
if ('contains' in $box[0] && !$box[0].contains(e.target) && e.target !== $overlay[0]) {
e.stopPropagation();
$box.focus();
}
}
function setClass(str) {
if (setClass.str !== str) {
$box.add($overlay).removeClass(setClass.str).addClass(str);
setClass.str = str;
}
}
function getRelated(rel) {
index = 0;
if (rel && rel !== false && rel !== 'nofollow') {
$related = $('.' + boxElement).filter(function () {
var options = $.data(this, colorbox);
var settings = new Settings(this, options);
return (settings.get('rel') === rel);
});
index = $related.index(settings.el);
if (index === -1) {
$related = $related.add(settings.el);
index = $related.length - 1;
}
} else {
$related = $(settings.el);
}
}
function trigger(event) {
$(document).trigger(event);
$events.triggerHandler(event);
}
var slideshow = (function(){
var active,
className = prefix + "Slideshow_",
click = "click." + prefix,
timeOut;
function clear () {
clearTimeout(timeOut);
}
function set() {
if (settings.get('loop') || $related[index + 1]) {
clear();
timeOut = setTimeout(publicMethod.next, settings.get('slideshowSpeed'));
}
}
function start() {
$slideshow
.html(settings.get('slideshowStop'))
.unbind(click)
.one(click, stop);
$events
.bind(event_complete, set)
.bind(event_load, clear);
$box.removeClass(className + "off").addClass(className + "on");
}
function stop() {
clear();
$events
.unbind(event_complete, set)
.unbind(event_load, clear);
$slideshow
.html(settings.get('slideshowStart'))
.unbind(click)
.one(click, function () {
publicMethod.next();
start();
});
$box.removeClass(className + "on").addClass(className + "off");
}
function reset() {
active = false;
$slideshow.hide();
clear();
$events
.unbind(event_complete, set)
.unbind(event_load, clear);
$box.removeClass(className + "off " + className + "on");
}
return function(){
if (active) {
if (!settings.get('slideshow')) {
$events.unbind(event_cleanup, reset);
reset();
}
} else {
if (settings.get('slideshow') && $related[1]) {
active = true;
$events.one(event_cleanup, reset);
if (settings.get('slideshowAuto')) {
start();
} else {
stop();
}
$slideshow.show();
}
}
};
}());
function launch(element) {
var options;
if (!closing) {
options = $(element).data(colorbox);
settings = new Settings(element, options);
getRelated(settings.get('rel'));
if (!open) {
open = active = true; // Prevents the page-change action from queuing up if the visitor holds down the left or right keys.
setClass(settings.get('className'));
$box.css({visibility:'hidden', display:'block', opacity:''});
$loaded = $tag(div, 'LoadedContent', 'width:0; height:0; overflow:hidden; visibility:hidden');
$content.css({width:'', height:''}).append($loaded);
interfaceHeight = $topBorder.height() + $bottomBorder.height() + $content.outerHeight(true) - $content.height();
interfaceWidth = $leftBorder.width() + $rightBorder.width() + $content.outerWidth(true) - $content.width();
loadedHeight = $loaded.outerHeight(true);
loadedWidth = $loaded.outerWidth(true);
var initialWidth = setSize(settings.get('initialWidth'), 'x');
var initialHeight = setSize(settings.get('initialHeight'), 'y');
var maxWidth = settings.get('maxWidth');
var maxHeight = settings.get('maxHeight');
settings.w = Math.max((maxWidth !== false ? Math.min(initialWidth, setSize(maxWidth, 'x')) : initialWidth) - loadedWidth - interfaceWidth, 0);
settings.h = Math.max((maxHeight !== false ? Math.min(initialHeight, setSize(maxHeight, 'y')) : initialHeight) - loadedHeight - interfaceHeight, 0);
$loaded.css({width:'', height:settings.h});
publicMethod.position();
trigger(event_open);
settings.get('onOpen');
$groupControls.add($title).hide();
$box.focus();
if (settings.get('trapFocus')) {
if (document.addEventListener) {
document.addEventListener('focus', trapFocus, true);
$events.one(event_closed, function () {
document.removeEventListener('focus', trapFocus, true);
});
}
}
if (settings.get('returnFocus')) {
$events.one(event_closed, function () {
$(settings.el).focus();
});
}
}
var opacity = parseFloat(settings.get('opacity'));
$overlay.css({
opacity: opacity === opacity ? opacity : '',
cursor: settings.get('overlayClose') ? 'pointer' : '',
visibility: 'visible'
}).show();
if (settings.get('closeButton')) {
$close.html(settings.get('close')).appendTo($content);
} else {
$close.appendTo(''); // replace with .detach() when dropping jQuery < 1.4
}
load();
}
}
function appendHTML() {
if (!$box) {
init = false;
$window = $(window);
$box = $tag(div).attr({
id: colorbox,
'class': $.support.opacity === false ? prefix + 'IE' : '', // class for optional IE8 & lower targeted CSS.
role: 'dialog',
tabindex: '-1'
}).hide();
$overlay = $tag(div, "Overlay").hide();
$loadingOverlay = $([$tag(div, "LoadingOverlay")[0],$tag(div, "LoadingGraphic")[0]]);
$wrap = $tag(div, "Wrapper");
$content = $tag(div, "Content").append(
$title = $tag(div, "Title"),
$current = $tag(div, "Current"),
$prev = $('').attr({id:prefix+'Previous'}),
$next = $('').attr({id:prefix+'Next'}),
$slideshow = $('').attr({id:prefix+'Slideshow'}),
$loadingOverlay
);
$close = $('').attr({id:prefix+'Close'});
$wrap.append( // The 3x3 Grid that makes up Colorbox
$tag(div).append(
$tag(div, "TopLeft"),
$topBorder = $tag(div, "TopCenter"),
$tag(div, "TopRight")
),
$tag(div, false, 'clear:left').append(
$leftBorder = $tag(div, "MiddleLeft"),
$content,
$rightBorder = $tag(div, "MiddleRight")
),
$tag(div, false, 'clear:left').append(
$tag(div, "BottomLeft"),
$bottomBorder = $tag(div, "BottomCenter"),
$tag(div, "BottomRight")
)
).find('div div').css({'float': 'left'});
$loadingBay = $tag(div, false, 'position:absolute; width:9999px; visibility:hidden; display:none; max-width:none;');
$groupControls = $next.add($prev).add($current).add($slideshow);
}
if (document.body && !$box.parent().length) {
$(document.body).append($overlay, $box.append($wrap, $loadingBay));
}
}
function addBindings() {
function clickHandler(e) {
if (!(e.which > 1 || e.shiftKey || e.altKey || e.metaKey || e.ctrlKey)) {
e.preventDefault();
launch(this);
}
}
if ($box) {
if (!init) {
init = true;
$next.click(function () {
publicMethod.next();
});
$prev.click(function () {
publicMethod.prev();
});
$close.click(function () {
publicMethod.close();
});
$overlay.click(function () {
if (settings.get('overlayClose')) {
publicMethod.close();
}
});
$(document).bind('keydown.' + prefix, function (e) {
var key = e.keyCode;
if (open && settings.get('escKey') && key === 27) {
e.preventDefault();
publicMethod.close();
}
if (open && settings.get('arrowKey') && $related[1] && !e.altKey) {
if (key === 37) {
e.preventDefault();
$prev.click();
} else if (key === 39) {
e.preventDefault();
$next.click();
}
}
});
if ($.isFunction($.fn.on)) {
$(document).on('click.'+prefix, '.'+boxElement, clickHandler);
} else {
$('.'+boxElement).live('click.'+prefix, clickHandler);
}
}
return true;
}
return false;
}
if ($[colorbox]) {
return;
}
$(appendHTML);
publicMethod = $.fn[colorbox] = $[colorbox] = function (options, callback) {
var settings;
var $obj = this;
options = options || {};
if ($.isFunction($obj)) { // assume a call to $.colorbox
$obj = $('');
options.open = true;
}
if (!$obj[0]) { // colorbox being applied to empty collection
return $obj;
}
appendHTML();
if (addBindings()) {
if (callback) {
options.onComplete = callback;
}
$obj.each(function () {
var old = $.data(this, colorbox) || {};
$.data(this, colorbox, $.extend(old, options));
}).addClass(boxElement);
settings = new Settings($obj[0], options);
if (settings.get('open')) {
launch($obj[0]);
}
}
return $obj;
};
publicMethod.position = function (speed, loadedCallback) {
var
css,
top = 0,
left = 0,
offset = $box.offset(),
scrollTop,
scrollLeft;
$window.unbind('resize.' + prefix);
$box.css({top: -9e4, left: -9e4});
scrollTop = $window.scrollTop();
scrollLeft = $window.scrollLeft();
if (settings.get('fixed')) {
offset.top -= scrollTop;
offset.left -= scrollLeft;
$box.css({position: 'fixed'});
} else {
top = scrollTop;
left = scrollLeft;
$box.css({position: 'absolute'});
}
if (settings.get('right') !== false) {
left += Math.max($window.width() - settings.w - loadedWidth - interfaceWidth - setSize(settings.get('right'), 'x'), 0);
} else if (settings.get('left') !== false) {
left += setSize(settings.get('left'), 'x');
} else {
left += Math.round(Math.max($window.width() - settings.w - loadedWidth - interfaceWidth, 0) / 2);
}
if (settings.get('bottom') !== false) {
top += Math.max(winheight() - settings.h - loadedHeight - interfaceHeight - setSize(settings.get('bottom'), 'y'), 0);
} else if (settings.get('top') !== false) {
top += setSize(settings.get('top'), 'y');
} else {
top += Math.round(Math.max(winheight() - settings.h - loadedHeight - interfaceHeight, 0) / 2);
}
$box.css({top: offset.top, left: offset.left, visibility:'visible'});
$wrap[0].style.width = $wrap[0].style.height = "9999px";
function modalDimensions() {
$topBorder[0].style.width = $bottomBorder[0].style.width = $content[0].style.width = (parseInt($box[0].style.width,10) - interfaceWidth)+'px';
$content[0].style.height = $leftBorder[0].style.height = $rightBorder[0].style.height = (parseInt($box[0].style.height,10) - interfaceHeight)+'px';
}
css = {width: settings.w + loadedWidth + interfaceWidth, height: settings.h + loadedHeight + interfaceHeight, top: top, left: left};
if (speed) {
var tempSpeed = 0;
$.each(css, function(i){
if (css[i] !== previousCSS[i]) {
tempSpeed = speed;
return;
}
});
speed = tempSpeed;
}
previousCSS = css;
if (!speed) {
$box.css(css);
}
$box.dequeue().animate(css, {
duration: speed || 0,
complete: function () {
modalDimensions();
active = false;
$wrap[0].style.width = (settings.w + loadedWidth + interfaceWidth) + "px";
$wrap[0].style.height = (settings.h + loadedHeight + interfaceHeight) + "px";
if (settings.get('reposition')) {
setTimeout(function () { // small delay before binding onresize due to an IE8 bug.
$window.bind('resize.' + prefix, publicMethod.position);
}, 1);
}
if ($.isFunction(loadedCallback)) {
loadedCallback();
}
},
step: modalDimensions
});
};
publicMethod.resize = function (options) {
var scrolltop;
if (open) {
options = options || {};
if (options.width) {
settings.w = setSize(options.width, 'x') - loadedWidth - interfaceWidth;
}
if (options.innerWidth) {
settings.w = setSize(options.innerWidth, 'x');
}
$loaded.css({width: settings.w});
if (options.height) {
settings.h = setSize(options.height, 'y') - loadedHeight - interfaceHeight;
}
if (options.innerHeight) {
settings.h = setSize(options.innerHeight, 'y');
}
if (!options.innerHeight && !options.height) {
scrolltop = $loaded.scrollTop();
$loaded.css({height: "auto"});
settings.h = $loaded.height();
}
$loaded.css({height: settings.h});
if(scrolltop) {
$loaded.scrollTop(scrolltop);
}
publicMethod.position(settings.get('transition') === "none" ? 0 : settings.get('speed'));
}
};
publicMethod.prep = function (object) {
if (!open) {
return;
}
var callback, speed = settings.get('transition') === "none" ? 0 : settings.get('speed');
$loaded.remove();
$loaded = $tag(div, 'LoadedContent').append(object);
function getWidth() {
settings.w = settings.w || $loaded.width();
settings.w = settings.mw && settings.mw < settings.w ? settings.mw : settings.w;
return settings.w;
}
function getHeight() {
settings.h = settings.h || $loaded.height();
settings.h = settings.mh && settings.mh < settings.h ? settings.mh : settings.h;
return settings.h;
}
$loaded.hide()
.appendTo($loadingBay.show())// content has to be appended to the DOM for accurate size calculations.
.css({width: getWidth(), overflow: settings.get('scrolling') ? 'auto' : 'hidden'})
.css({height: getHeight()})// sets the height independently from the width in case the new width influences the value of height.
.prependTo($content);
$loadingBay.hide();
$(photo).css({'float': 'none'});
setClass(settings.get('className'));
callback = function () {
var total = $related.length,
iframe,
complete;
if (!open) {
return;
}
function removeFilter() { // Needed for IE8 in versions of jQuery prior to 1.7.2
if ($.support.opacity === false) {
$box[0].style.removeAttribute('filter');
}
}
complete = function () {
clearTimeout(loadingTimer);
$loadingOverlay.hide();
trigger(event_complete);
settings.get('onComplete');
};
$title.html(settings.get('title')).show();
$loaded.show();
if (total > 1) { // handle grouping
if (typeof settings.get('current') === "string") {
$current.html(settings.get('current').replace('{current}', index + 1).replace('{total}', total)).show();
}
$next[(settings.get('loop') || index < total - 1) ? "show" : "hide"]().html(settings.get('next'));
$prev[(settings.get('loop') || index) ? "show" : "hide"]().html(settings.get('previous'));
slideshow();
if (settings.get('preloading')) {
$.each([getIndex(-1), getIndex(1)], function(){
var img,
i = $related[this],
settings = new Settings(i, $.data(i, colorbox)),
src = settings.get('href');
if (src && isImage(settings, src)) {
src = retinaUrl(settings, src);
img = document.createElement('img');
img.src = src;
}
});
}
} else {
$groupControls.hide();
}
if (settings.get('iframe')) {
iframe = settings.get('createIframe');
if (!settings.get('scrolling')) {
iframe.scrolling = "no";
}
$(iframe)
.attr({
src: settings.get('href'),
'class': prefix + 'Iframe'
})
.one('load', complete)
.appendTo($loaded);
$events.one(event_purge, function () {
iframe.src = "//about:blank";
});
if (settings.get('fastIframe')) {
$(iframe).trigger('load');
}
} else {
complete();
}
if (settings.get('transition') === 'fade') {
$box.fadeTo(speed, 1, removeFilter);
} else {
removeFilter();
}
};
if (settings.get('transition') === 'fade') {
$box.fadeTo(speed, 0, function () {
publicMethod.position(0, callback);
});
} else {
publicMethod.position(speed, callback);
}
};
function load () {
var href, setResize, prep = publicMethod.prep, $inline, request = ++requests;
active = true;
photo = false;
trigger(event_purge);
trigger(event_load);
settings.get('onLoad');
settings.h = settings.get('height') ?
setSize(settings.get('height'), 'y') - loadedHeight - interfaceHeight :
settings.get('innerHeight') && setSize(settings.get('innerHeight'), 'y');
settings.w = settings.get('width') ?
setSize(settings.get('width'), 'x') - loadedWidth - interfaceWidth :
settings.get('innerWidth') && setSize(settings.get('innerWidth'), 'x');
settings.mw = settings.w;
settings.mh = settings.h;
if (settings.get('maxWidth')) {
settings.mw = setSize(settings.get('maxWidth'), 'x') - loadedWidth - interfaceWidth;
settings.mw = settings.w && settings.w < settings.mw ? settings.w : settings.mw;
}
if (settings.get('maxHeight')) {
settings.mh = setSize(settings.get('maxHeight'), 'y') - loadedHeight - interfaceHeight;
settings.mh = settings.h && settings.h < settings.mh ? settings.h : settings.mh;
}
href = settings.get('href');
loadingTimer = setTimeout(function () {
$loadingOverlay.show();
}, 100);
if (settings.get('inline')) {
var $target = $(href).eq(0);
$inline = $('
').hide().insertBefore($target);
$events.one(event_purge, function () {
$inline.replaceWith($target);
});
prep($target);
} else if (settings.get('iframe')) {
prep(" ");
} else if (settings.get('html')) {
prep(settings.get('html'));
} else if (isImage(settings, href)) {
href = retinaUrl(settings, href);
photo = settings.get('createImg');
$(photo)
.addClass(prefix + 'Photo')
.bind('error.'+prefix,function () {
prep($tag(div, 'Error').html(settings.get('imgError')));
})
.one('load', function () {
if (request !== requests) {
return;
}
setTimeout(function(){
var percent;
if (settings.get('retinaImage') && window.devicePixelRatio > 1) {
photo.height = photo.height / window.devicePixelRatio;
photo.width = photo.width / window.devicePixelRatio;
}
if (settings.get('scalePhotos')) {
setResize = function () {
photo.height -= photo.height * percent;
photo.width -= photo.width * percent;
};
if (settings.mw && photo.width > settings.mw) {
percent = (photo.width - settings.mw) / photo.width;
setResize();
}
if (settings.mh && photo.height > settings.mh) {
percent = (photo.height - settings.mh) / photo.height;
setResize();
}
}
if (settings.h) {
photo.style.marginTop = Math.max(settings.mh - photo.height, 0) / 2 + 'px';
}
if ($related[1] && (settings.get('loop') || $related[index + 1])) {
photo.style.cursor = 'pointer';
$(photo).bind('click.'+prefix, function () {
publicMethod.next();
});
}
photo.style.width = photo.width + 'px';
photo.style.height = photo.height + 'px';
prep(photo);
}, 1);
});
photo.src = href;
} else if (href) {
$loadingBay.load(href, settings.get('data'), function (data, status) {
if (request === requests) {
prep(status === 'error' ? $tag(div, 'Error').html(settings.get('xhrError')) : $(this).contents());
}
});
}
}
publicMethod.next = function () {
if (!active && $related[1] && (settings.get('loop') || $related[index + 1])) {
index = getIndex(1);
launch($related[index]);
}
};
publicMethod.prev = function () {
if (!active && $related[1] && (settings.get('loop') || index)) {
index = getIndex(-1);
launch($related[index]);
}
};
publicMethod.close = function () {
if (open && !closing) {
closing = true;
open = false;
trigger(event_cleanup);
settings.get('onCleanup');
$window.unbind('.' + prefix);
$overlay.fadeTo(settings.get('fadeOut') || 0, 0);
$box.stop().fadeTo(settings.get('fadeOut') || 0, 0, function () {
$box.hide();
$overlay.hide();
trigger(event_purge);
$loaded.remove();
setTimeout(function () {
closing = false;
trigger(event_closed);
settings.get('onClosed');
}, 1);
});
}
};
publicMethod.remove = function () {
if (!$box) { return; }
$box.stop();
$[colorbox].close();
$box.stop(false, true).remove();
$overlay.remove();
closing = false;
$box = null;
$('.' + boxElement)
.removeData(colorbox)
.removeClass(boxElement);
$(document).unbind('click.'+prefix).unbind('keydown.'+prefix);
};
publicMethod.element = function () {
return $(settings.el);
};
publicMethod.settings = defaults;
}(jQuery, document, window));/*!
* jQuery Validation Plugin v1.14.0
*
* http://jqueryvalidation.org/
*
* Copyright (c) 2015 Jörn Zaefferer
* Released under the MIT license
*/
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
define( ["jquery"], factory );
} else {
factory( jQuery );
}
}(function( $ ) {
$.extend($.fn, {
validate: function( options ) {
if ( !this.length ) {
if ( options && options.debug && window.console ) {
console.warn( "Nothing selected, can't validate, returning nothing." );
}
return;
}
var validator = $.data( this[ 0 ], "validator" );
if ( validator ) {
return validator;
}
this.attr( "novalidate", "novalidate" );
validator = new $.validator( options, this[ 0 ] );
$.data( this[ 0 ], "validator", validator );
if ( validator.settings.onsubmit ) {
this.on( "click.validate", ":submit", function( event ) {
if ( validator.settings.submitHandler ) {
validator.submitButton = event.target;
}
if ( $( this ).hasClass( "cancel" ) ) {
validator.cancelSubmit = true;
}
if ( $( this ).attr( "formnovalidate" ) !== undefined ) {
validator.cancelSubmit = true;
}
});
this.on( "submit.validate", function( event ) {
if ( validator.settings.debug ) {
event.preventDefault();
}
function handle() {
var hidden, result;
if ( validator.settings.submitHandler ) {
if ( validator.submitButton ) {
hidden = $( "" )
.attr( "name", validator.submitButton.name )
.val( $( validator.submitButton ).val() )
.appendTo( validator.currentForm );
}
result = validator.settings.submitHandler.call( validator, validator.currentForm, event );
if ( validator.submitButton ) {
hidden.remove();
}
if ( result !== undefined ) {
return result;
}
return false;
}
return true;
}
if ( validator.cancelSubmit ) {
validator.cancelSubmit = false;
return handle();
}
if ( validator.form() ) {
if ( validator.pendingRequest ) {
validator.formSubmitted = true;
return false;
}
return handle();
} else {
validator.focusInvalid();
return false;
}
});
}
return validator;
},
valid: function() {
var valid, validator, errorList;
if ( $( this[ 0 ] ).is( "form" ) ) {
valid = this.validate().form();
} else {
errorList = [];
valid = true;
validator = $( this[ 0 ].form ).validate();
this.each( function() {
valid = validator.element( this ) && valid;
errorList = errorList.concat( validator.errorList );
});
validator.errorList = errorList;
}
return valid;
},
rules: function( command, argument ) {
var element = this[ 0 ],
settings, staticRules, existingRules, data, param, filtered;
if ( command ) {
settings = $.data( element.form, "validator" ).settings;
staticRules = settings.rules;
existingRules = $.validator.staticRules( element );
switch ( command ) {
case "add":
$.extend( existingRules, $.validator.normalizeRule( argument ) );
delete existingRules.messages;
staticRules[ element.name ] = existingRules;
if ( argument.messages ) {
settings.messages[ element.name ] = $.extend( settings.messages[ element.name ], argument.messages );
}
break;
case "remove":
if ( !argument ) {
delete staticRules[ element.name ];
return existingRules;
}
filtered = {};
$.each( argument.split( /\s/ ), function( index, method ) {
filtered[ method ] = existingRules[ method ];
delete existingRules[ method ];
if ( method === "required" ) {
$( element ).removeAttr( "aria-required" );
}
});
return filtered;
}
}
data = $.validator.normalizeRules(
$.extend(
{},
$.validator.classRules( element ),
$.validator.attributeRules( element ),
$.validator.dataRules( element ),
$.validator.staticRules( element )
), element );
if ( data.required ) {
param = data.required;
delete data.required;
data = $.extend( { required: param }, data );
$( element ).attr( "aria-required", "true" );
}
if ( data.remote ) {
param = data.remote;
delete data.remote;
data = $.extend( data, { remote: param });
}
return data;
}
});
$.extend( $.expr[ ":" ], {
blank: function( a ) {
return !$.trim( "" + $( a ).val() );
},
filled: function( a ) {
return !!$.trim( "" + $( a ).val() );
},
unchecked: function( a ) {
return !$( a ).prop( "checked" );
}
});
$.validator = function( options, form ) {
this.settings = $.extend( true, {}, $.validator.defaults, options );
this.currentForm = form;
this.init();
};
$.validator.format = function( source, params ) {
if ( arguments.length === 1 ) {
return function() {
var args = $.makeArray( arguments );
args.unshift( source );
return $.validator.format.apply( this, args );
};
}
if ( arguments.length > 2 && params.constructor !== Array ) {
params = $.makeArray( arguments ).slice( 1 );
}
if ( params.constructor !== Array ) {
params = [ params ];
}
$.each( params, function( i, n ) {
source = source.replace( new RegExp( "\\{" + i + "\\}", "g" ), function() {
return n;
});
});
return source;
};
$.extend( $.validator, {
defaults: {
messages: {},
groups: {},
rules: {},
errorClass: "error",
validClass: "valid",
errorElement: "label",
focusCleanup: false,
focusInvalid: true,
errorContainer: $( [] ),
errorLabelContainer: $( [] ),
onsubmit: true,
ignore: ":hidden",
ignoreTitle: false,
onfocusin: function( element ) {
this.lastActive = element;
if ( this.settings.focusCleanup ) {
if ( this.settings.unhighlight ) {
this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass );
}
this.hideThese( this.errorsFor( element ) );
}
},
onfocusout: function( element ) {
if ( !this.checkable( element ) && ( element.name in this.submitted || !this.optional( element ) ) ) {
this.element( element );
}
},
onkeyup: function( element, event ) {
var excludedKeys = [
16, 17, 18, 20, 35, 36, 37,
38, 39, 40, 45, 144, 225
];
if ( event.which === 9 && this.elementValue( element ) === "" || $.inArray( event.keyCode, excludedKeys ) !== -1 ) {
return;
} else if ( element.name in this.submitted || element === this.lastElement ) {
this.element( element );
}
},
onclick: function( element ) {
if ( element.name in this.submitted ) {
this.element( element );
} else if ( element.parentNode.name in this.submitted ) {
this.element( element.parentNode );
}
},
highlight: function( element, errorClass, validClass ) {
if ( element.type === "radio" ) {
this.findByName( element.name ).addClass( errorClass ).removeClass( validClass );
} else {
$( element ).addClass( errorClass ).removeClass( validClass );
}
},
unhighlight: function( element, errorClass, validClass ) {
if ( element.type === "radio" ) {
this.findByName( element.name ).removeClass( errorClass ).addClass( validClass );
} else {
$( element ).removeClass( errorClass ).addClass( validClass );
}
}
},
setDefaults: function( settings ) {
$.extend( $.validator.defaults, settings );
},
messages: {
required: "This field is required.",
remote: "Please fix this field.",
email: "Please enter a valid email address.",
url: "Please enter a valid URL.",
date: "Please enter a valid date.",
dateISO: "Please enter a valid date ( ISO ).",
number: "Please enter a valid number.",
digits: "Please enter only digits.",
creditcard: "Please enter a valid credit card number.",
equalTo: "Please enter the same value again.",
maxlength: $.validator.format( "Please enter no more than {0} characters." ),
minlength: $.validator.format( "Please enter at least {0} characters." ),
rangelength: $.validator.format( "Please enter a value between {0} and {1} characters long." ),
range: $.validator.format( "Please enter a value between {0} and {1}." ),
max: $.validator.format( "Please enter a value less than or equal to {0}." ),
min: $.validator.format( "Please enter a value greater than or equal to {0}." )
},
autoCreateRanges: false,
prototype: {
init: function() {
this.labelContainer = $( this.settings.errorLabelContainer );
this.errorContext = this.labelContainer.length && this.labelContainer || $( this.currentForm );
this.containers = $( this.settings.errorContainer ).add( this.settings.errorLabelContainer );
this.submitted = {};
this.valueCache = {};
this.pendingRequest = 0;
this.pending = {};
this.invalid = {};
this.reset();
var groups = ( this.groups = {} ),
rules;
$.each( this.settings.groups, function( key, value ) {
if ( typeof value === "string" ) {
value = value.split( /\s/ );
}
$.each( value, function( index, name ) {
groups[ name ] = key;
});
});
rules = this.settings.rules;
$.each( rules, function( key, value ) {
rules[ key ] = $.validator.normalizeRule( value );
});
function delegate( event ) {
/**
* SITE123 Bug-fix - We had some JS errors when using the Custom Form
* so we added this script to handle that. To reproduce add a check-box
* to any custom form at the interface and set it as require, then click
* on it and see the JS error.
* e.g. eCommerce >> Edit >> Configuration >> Custom Form
*/
if ( !this.form ) return;
var validator = $.data( this.form, "validator" ),
eventType = "on" + event.type.replace( /^validate/, "" ),
settings = validator.settings;
if ( settings[ eventType ] && !$( this ).is( settings.ignore ) ) {
settings[ eventType ].call( validator, this, event );
}
}
$( this.currentForm )
.on( "focusin.validate focusout.validate keyup.validate",
":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], " +
"[type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], " +
"[type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], " +
"[type='radio'], [type='checkbox']", delegate)
.on("click.validate", "select, option, [type='radio'], [type='checkbox']", delegate);
if ( this.settings.invalidHandler ) {
$( this.currentForm ).on( "invalid-form.validate", this.settings.invalidHandler );
}
$( this.currentForm ).find( "[required], [data-rule-required], .required" ).attr( "aria-required", "true" );
},
form: function() {
this.checkForm();
$.extend( this.submitted, this.errorMap );
this.invalid = $.extend({}, this.errorMap );
if ( !this.valid() ) {
$( this.currentForm ).triggerHandler( "invalid-form", [ this ]);
}
this.showErrors();
return this.valid();
},
checkForm: function() {
this.prepareForm();
for ( var i = 0, elements = ( this.currentElements = this.elements() ); elements[ i ]; i++ ) {
this.check( elements[ i ] );
}
return this.valid();
},
element: function( element ) {
var cleanElement = this.clean( element ),
checkElement = this.validationTargetFor( cleanElement ),
result = true;
this.lastElement = checkElement;
if ( checkElement === undefined ) {
delete this.invalid[ cleanElement.name ];
} else {
this.prepareElement( checkElement );
this.currentElements = $( checkElement );
result = this.check( checkElement ) !== false;
if ( result ) {
delete this.invalid[ checkElement.name ];
} else {
this.invalid[ checkElement.name ] = true;
}
}
$( element ).attr( "aria-invalid", !result );
if ( !this.numberOfInvalids() ) {
this.toHide = this.toHide.add( this.containers );
}
this.showErrors();
return result;
},
showErrors: function( errors ) {
if ( errors ) {
$.extend( this.errorMap, errors );
this.errorList = [];
for ( var name in errors ) {
this.errorList.push({
message: errors[ name ],
element: this.findByName( name )[ 0 ]
});
}
this.successList = $.grep( this.successList, function( element ) {
return !( element.name in errors );
});
}
if ( this.settings.showErrors ) {
this.settings.showErrors.call( this, this.errorMap, this.errorList );
} else {
this.defaultShowErrors();
}
},
resetForm: function() {
if ( $.fn.resetForm ) {
$( this.currentForm ).resetForm();
}
this.submitted = {};
this.lastElement = null;
this.prepareForm();
this.hideErrors();
var i, elements = this.elements()
.removeData( "previousValue" )
.removeAttr( "aria-invalid" );
if ( this.settings.unhighlight ) {
for ( i = 0; elements[ i ]; i++ ) {
this.settings.unhighlight.call( this, elements[ i ],
this.settings.errorClass, "" );
}
} else {
elements.removeClass( this.settings.errorClass );
}
},
numberOfInvalids: function() {
return this.objectLength( this.invalid );
},
objectLength: function( obj ) {
/* jshint unused: false */
var count = 0,
i;
for ( i in obj ) {
count++;
}
return count;
},
hideErrors: function() {
this.hideThese( this.toHide );
},
hideThese: function( errors ) {
errors.not( this.containers ).text( "" );
this.addWrapper( errors ).hide();
},
valid: function() {
return this.size() === 0;
},
size: function() {
return this.errorList.length;
},
focusInvalid: function() {
if ( this.settings.focusInvalid ) {
try {
$( this.findLastActive() || this.errorList.length && this.errorList[ 0 ].element || [])
.filter( ":visible" )
.focus()
.trigger( "focusin" );
} catch ( e ) {
}
}
},
findLastActive: function() {
var lastActive = this.lastActive;
return lastActive && $.grep( this.errorList, function( n ) {
return n.element.name === lastActive.name;
}).length === 1 && lastActive;
},
elements: function() {
var validator = this,
rulesCache = {};
return $( this.currentForm )
.find( "input, select, textarea" )
.not( ":submit, :reset, :image, :disabled" )
.not( this.settings.ignore )
.filter( function() {
if ( !this.name && validator.settings.debug && window.console ) {
console.error( "%o has no name assigned", this );
}
if ( this.name in rulesCache || !validator.objectLength( $( this ).rules() ) ) {
return false;
}
rulesCache[ this.name ] = true;
return true;
});
},
clean: function( selector ) {
return $( selector )[ 0 ];
},
errors: function() {
var errorClass = this.settings.errorClass.split( " " ).join( "." );
return $( this.settings.errorElement + "." + errorClass, this.errorContext );
},
reset: function() {
this.successList = [];
this.errorList = [];
this.errorMap = {};
this.toShow = $( [] );
this.toHide = $( [] );
this.currentElements = $( [] );
},
prepareForm: function() {
this.reset();
this.toHide = this.errors().add( this.containers );
},
prepareElement: function( element ) {
this.reset();
this.toHide = this.errorsFor( element );
},
elementValue: function( element ) {
var val,
$element = $( element ),
type = element.type;
if ( type === "radio" || type === "checkbox" ) {
return this.findByName( element.name ).filter(":checked").val();
} else if ( type === "number" && typeof element.validity !== "undefined" ) {
return element.validity.badInput ? false : $element.val();
}
val = $element.val();
if ( typeof val === "string" ) {
return val.replace(/\r/g, "" );
}
return val;
},
check: function( element ) {
element = this.validationTargetFor( this.clean( element ) );
var rules = $( element ).rules(),
rulesCount = $.map( rules, function( n, i ) {
return i;
}).length,
dependencyMismatch = false,
val = this.elementValue( element ),
result, method, rule;
for ( method in rules ) {
rule = { method: method, parameters: rules[ method ] };
try {
result = $.validator.methods[ method ].call( this, val, element, rule.parameters );
if ( result === "dependency-mismatch" && rulesCount === 1 ) {
dependencyMismatch = true;
continue;
}
dependencyMismatch = false;
if ( result === "pending" ) {
this.toHide = this.toHide.not( this.errorsFor( element ) );
return;
}
if ( !result ) {
this.formatAndAdd( element, rule );
return false;
}
} catch ( e ) {
if ( this.settings.debug && window.console ) {
console.log( "Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.", e );
}
if ( e instanceof TypeError ) {
e.message += ". Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.";
}
throw e;
}
}
if ( dependencyMismatch ) {
return;
}
if ( this.objectLength( rules ) ) {
this.successList.push( element );
}
return true;
},
customDataMessage: function( element, method ) {
return $( element ).data( "msg" + method.charAt( 0 ).toUpperCase() +
method.substring( 1 ).toLowerCase() ) || $( element ).data( "msg" );
},
customMessage: function( name, method ) {
var m = this.settings.messages[ name ];
return m && ( m.constructor === String ? m : m[ method ]);
},
findDefined: function() {
for ( var i = 0; i < arguments.length; i++) {
if ( arguments[ i ] !== undefined ) {
return arguments[ i ];
}
}
return undefined;
},
defaultMessage: function( element, method ) {
return this.findDefined(
this.customMessage( element.name, method ),
this.customDataMessage( element, method ),
!this.settings.ignoreTitle && element.title || undefined,
$.validator.messages[ method ],
"Warning: No message defined for " + element.name + ""
);
},
formatAndAdd: function( element, rule ) {
var message = this.defaultMessage( element, rule.method ),
theregex = /\$?\{(\d+)\}/g;
if ( typeof message === "function" ) {
message = message.call( this, rule.parameters, element );
} else if ( theregex.test( message ) ) {
message = $.validator.format( message.replace( theregex, "{$1}" ), rule.parameters );
}
this.errorList.push({
message: message,
element: element,
method: rule.method
});
this.errorMap[ element.name ] = message;
this.submitted[ element.name ] = message;
},
addWrapper: function( toToggle ) {
if ( this.settings.wrapper ) {
toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) );
}
return toToggle;
},
defaultShowErrors: function() {
var i, elements, error;
for ( i = 0; this.errorList[ i ]; i++ ) {
error = this.errorList[ i ];
if ( this.settings.highlight ) {
this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );
}
this.showLabel( error.element, error.message );
}
if ( this.errorList.length ) {
this.toShow = this.toShow.add( this.containers );
}
if ( this.settings.success ) {
for ( i = 0; this.successList[ i ]; i++ ) {
this.showLabel( this.successList[ i ] );
}
}
if ( this.settings.unhighlight ) {
for ( i = 0, elements = this.validElements(); elements[ i ]; i++ ) {
this.settings.unhighlight.call( this, elements[ i ], this.settings.errorClass, this.settings.validClass );
}
}
this.toHide = this.toHide.not( this.toShow );
this.hideErrors();
this.addWrapper( this.toShow ).show();
},
validElements: function() {
return this.currentElements.not( this.invalidElements() );
},
invalidElements: function() {
return $( this.errorList ).map(function() {
return this.element;
});
},
showLabel: function( element, message ) {
var place, group, errorID,
error = this.errorsFor( element ),
elementID = this.idOrName( element ),
describedBy = $( element ).attr( "aria-describedby" );
if ( error.length ) {
error.removeClass( this.settings.validClass ).addClass( this.settings.errorClass );
error.html( message );
} else {
error = $( "<" + this.settings.errorElement + ">" )
.attr( "id", elementID + "-error" )
.addClass( this.settings.errorClass )
.html( message || "" );
place = error;
if ( this.settings.wrapper ) {
place = error.hide().show().wrap( "<" + this.settings.wrapper + "/>" ).parent();
}
if ( this.labelContainer.length ) {
this.labelContainer.append( place );
} else if ( this.settings.errorPlacement ) {
this.settings.errorPlacement( place, $( element ) );
} else {
place.insertAfter( element );
}
if ( error.is( "label" ) ) {
error.attr( "for", elementID );
} else if ( error.parents( "label[for='" + elementID + "']" ).length === 0 ) {
errorID = error.attr( "id" ).replace( /(:|\.|\[|\]|\$)/g, "\\$1");
if ( !describedBy ) {
describedBy = errorID;
} else if ( !describedBy.match( new RegExp( "\\b" + errorID + "\\b" ) ) ) {
describedBy += " " + errorID;
}
$( element ).attr( "aria-describedby", describedBy );
group = this.groups[ element.name ];
if ( group ) {
$.each( this.groups, function( name, testgroup ) {
if ( testgroup === group ) {
$( "[name='" + name + "']", this.currentForm )
.attr( "aria-describedby", error.attr( "id" ) );
}
});
}
}
}
if ( !message && this.settings.success ) {
error.text( "" );
if ( typeof this.settings.success === "string" ) {
error.addClass( this.settings.success );
} else {
this.settings.success( error, element );
}
}
this.toShow = this.toShow.add( error );
},
errorsFor: function( element ) {
var name = this.idOrName( element ),
describer = $( element ).attr( "aria-describedby" ),
selector = "label[for='" + name + "'], label[for='" + name + "'] *";
if ( describer ) {
selector = selector + ", #" + describer.replace( /\s+/g, ", #" );
}
return this
.errors()
.filter( selector );
},
idOrName: function( element ) {
return this.groups[ element.name ] || ( this.checkable( element ) ? element.name : element.id || element.name );
},
validationTargetFor: function( element ) {
if ( this.checkable( element ) ) {
element = this.findByName( element.name );
}
return $( element ).not( this.settings.ignore )[ 0 ];
},
checkable: function( element ) {
return ( /radio|checkbox/i ).test( element.type );
},
findByName: function( name ) {
return $( this.currentForm ).find( "[name='" + name + "']" );
},
getLength: function( value, element ) {
switch ( element.nodeName.toLowerCase() ) {
case "select":
return $( "option:selected", element ).length;
case "input":
if ( this.checkable( element ) ) {
return this.findByName( element.name ).filter( ":checked" ).length;
}
}
return value.length;
},
depend: function( param, element ) {
return this.dependTypes[typeof param] ? this.dependTypes[typeof param]( param, element ) : true;
},
dependTypes: {
"boolean": function( param ) {
return param;
},
"string": function( param, element ) {
return !!$( param, element.form ).length;
},
"function": function( param, element ) {
return param( element );
}
},
optional: function( element ) {
var val = this.elementValue( element );
return !$.validator.methods.required.call( this, val, element ) && "dependency-mismatch";
},
startRequest: function( element ) {
if ( !this.pending[ element.name ] ) {
this.pendingRequest++;
this.pending[ element.name ] = true;
}
},
stopRequest: function( element, valid ) {
this.pendingRequest--;
if ( this.pendingRequest < 0 ) {
this.pendingRequest = 0;
}
delete this.pending[ element.name ];
if ( valid && this.pendingRequest === 0 && this.formSubmitted && this.form() ) {
$( this.currentForm ).submit();
this.formSubmitted = false;
} else if (!valid && this.pendingRequest === 0 && this.formSubmitted ) {
$( this.currentForm ).triggerHandler( "invalid-form", [ this ]);
this.formSubmitted = false;
}
},
previousValue: function( element ) {
return $.data( element, "previousValue" ) || $.data( element, "previousValue", {
old: null,
valid: true,
message: this.defaultMessage( element, "remote" )
});
},
destroy: function() {
this.resetForm();
$( this.currentForm )
.off( ".validate" )
.removeData( "validator" );
}
},
classRuleSettings: {
required: { required: true },
email: { email: true },
url: { url: true },
date: { date: true },
dateISO: { dateISO: true },
number: { number: true },
digits: { digits: true },
creditcard: { creditcard: true }
},
addClassRules: function( className, rules ) {
if ( className.constructor === String ) {
this.classRuleSettings[ className ] = rules;
} else {
$.extend( this.classRuleSettings, className );
}
},
classRules: function( element ) {
var rules = {},
classes = $( element ).attr( "class" );
if ( classes ) {
$.each( classes.split( " " ), function() {
if ( this in $.validator.classRuleSettings ) {
$.extend( rules, $.validator.classRuleSettings[ this ]);
}
});
}
return rules;
},
normalizeAttributeRule: function( rules, type, method, value ) {
if ( /min|max/.test( method ) && ( type === null || /number|range|text/.test( type ) ) ) {
value = Number( value );
if ( isNaN( value ) ) {
value = undefined;
}
}
if ( value || value === 0 ) {
rules[ method ] = value;
} else if ( type === method && type !== "range" ) {
rules[ method ] = true;
}
},
attributeRules: function( element ) {
var rules = {},
$element = $( element ),
type = element.getAttribute( "type" ),
method, value;
for ( method in $.validator.methods ) {
if ( method === "required" ) {
value = element.getAttribute( method );
if ( value === "" ) {
value = true;
}
value = !!value;
} else {
value = $element.attr( method );
}
this.normalizeAttributeRule( rules, type, method, value );
}
if ( rules.maxlength && /-1|2147483647|524288/.test( rules.maxlength ) ) {
delete rules.maxlength;
}
return rules;
},
dataRules: function( element ) {
var rules = {},
$element = $( element ),
type = element.getAttribute( "type" ),
method, value;
for ( method in $.validator.methods ) {
value = $element.data( "rule" + method.charAt( 0 ).toUpperCase() + method.substring( 1 ).toLowerCase() );
this.normalizeAttributeRule( rules, type, method, value );
}
return rules;
},
staticRules: function( element ) {
var rules = {},
validator = $.data( element.form, "validator" );
if ( validator.settings.rules ) {
rules = $.validator.normalizeRule( validator.settings.rules[ element.name ] ) || {};
}
return rules;
},
normalizeRules: function( rules, element ) {
$.each( rules, function( prop, val ) {
if ( val === false ) {
delete rules[ prop ];
return;
}
if ( val.param || val.depends ) {
var keepRule = true;
switch ( typeof val.depends ) {
case "string":
keepRule = !!$( val.depends, element.form ).length;
break;
case "function":
keepRule = val.depends.call( element, element );
break;
}
if ( keepRule ) {
rules[ prop ] = val.param !== undefined ? val.param : true;
} else {
delete rules[ prop ];
}
}
});
$.each( rules, function( rule, parameter ) {
rules[ rule ] = $.isFunction( parameter ) ? parameter( element ) : parameter;
});
$.each([ "minlength", "maxlength" ], function() {
if ( rules[ this ] ) {
rules[ this ] = Number( rules[ this ] );
}
});
$.each([ "rangelength", "range" ], function() {
var parts;
if ( rules[ this ] ) {
if ( $.isArray( rules[ this ] ) ) {
rules[ this ] = [ Number( rules[ this ][ 0 ]), Number( rules[ this ][ 1 ] ) ];
} else if ( typeof rules[ this ] === "string" ) {
parts = rules[ this ].replace(/[\[\]]/g, "" ).split( /[\s,]+/ );
rules[ this ] = [ Number( parts[ 0 ]), Number( parts[ 1 ] ) ];
}
}
});
if ( $.validator.autoCreateRanges ) {
if ( rules.min != null && rules.max != null ) {
rules.range = [ rules.min, rules.max ];
delete rules.min;
delete rules.max;
}
if ( rules.minlength != null && rules.maxlength != null ) {
rules.rangelength = [ rules.minlength, rules.maxlength ];
delete rules.minlength;
delete rules.maxlength;
}
}
return rules;
},
normalizeRule: function( data ) {
if ( typeof data === "string" ) {
var transformed = {};
$.each( data.split( /\s/ ), function() {
transformed[ this ] = true;
});
data = transformed;
}
return data;
},
addMethod: function( name, method, message ) {
$.validator.methods[ name ] = method;
$.validator.messages[ name ] = message !== undefined ? message : $.validator.messages[ name ];
if ( method.length < 3 ) {
$.validator.addClassRules( name, $.validator.normalizeRule( name ) );
}
},
methods: {
required: function( value, element, param ) {
if ( !this.depend( param, element ) ) {
return "dependency-mismatch";
}
if ( element.nodeName.toLowerCase() === "select" ) {
var val = $( element ).val();
return val && val.length > 0;
}
if ( this.checkable( element ) ) {
return this.getLength( value, element ) > 0;
}
return value.length > 0;
},
email: function( value, element ) {
return this.optional( element ) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test( value );
},
url: function( value, element ) {
return this.optional( element ) || /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test( value );
},
date: function( value, element ) {
return this.optional( element ) || !/Invalid|NaN/.test( new Date( value ).toString() );
},
dateISO: function( value, element ) {
return this.optional( element ) || /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test( value );
},
number: function( value, element ) {
return this.optional( element ) || /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test( value );
},
digits: function( value, element ) {
return this.optional( element ) || /^\d+$/.test( value );
},
creditcard: function( value, element ) {
if ( this.optional( element ) ) {
return "dependency-mismatch";
}
if ( /[^0-9 \-]+/.test( value ) ) {
return false;
}
var nCheck = 0,
nDigit = 0,
bEven = false,
n, cDigit;
value = value.replace( /\D/g, "" );
if ( value.length < 13 || value.length > 19 ) {
return false;
}
for ( n = value.length - 1; n >= 0; n--) {
cDigit = value.charAt( n );
nDigit = parseInt( cDigit, 10 );
if ( bEven ) {
if ( ( nDigit *= 2 ) > 9 ) {
nDigit -= 9;
}
}
nCheck += nDigit;
bEven = !bEven;
}
return ( nCheck % 10 ) === 0;
},
minlength: function( value, element, param ) {
var length = $.isArray( value ) ? value.length : this.getLength( value, element );
return this.optional( element ) || length >= param;
},
maxlength: function( value, element, param ) {
var length = $.isArray( value ) ? value.length : this.getLength( value, element );
return this.optional( element ) || length <= param;
},
rangelength: function( value, element, param ) {
var length = $.isArray( value ) ? value.length : this.getLength( value, element );
return this.optional( element ) || ( length >= param[ 0 ] && length <= param[ 1 ] );
},
min: function( value, element, param ) {
return this.optional( element ) || value >= param;
},
max: function( value, element, param ) {
return this.optional( element ) || value <= param;
},
range: function( value, element, param ) {
return this.optional( element ) || ( value >= param[ 0 ] && value <= param[ 1 ] );
},
equalTo: function( value, element, param ) {
var target = $( param );
if ( this.settings.onfocusout ) {
target.off( ".validate-equalTo" ).on( "blur.validate-equalTo", function() {
$( element ).valid();
});
}
return value === target.val();
},
remote: function( value, element, param ) {
if ( this.optional( element ) ) {
return "dependency-mismatch";
}
var previous = this.previousValue( element ),
validator, data;
if (!this.settings.messages[ element.name ] ) {
this.settings.messages[ element.name ] = {};
}
previous.originalMessage = this.settings.messages[ element.name ].remote;
this.settings.messages[ element.name ].remote = previous.message;
param = typeof param === "string" && { url: param } || param;
if ( previous.old === value ) {
return previous.valid;
}
previous.old = value;
validator = this;
this.startRequest( element );
data = {};
data[ element.name ] = value;
$.ajax( $.extend( true, {
mode: "abort",
port: "validate" + element.name,
dataType: "json",
data: data,
context: validator.currentForm,
success: function( response ) {
var valid = response === true || response === "true",
errors, message, submitted;
validator.settings.messages[ element.name ].remote = previous.originalMessage;
if ( valid ) {
submitted = validator.formSubmitted;
validator.prepareElement( element );
validator.formSubmitted = submitted;
validator.successList.push( element );
delete validator.invalid[ element.name ];
validator.showErrors();
} else {
errors = {};
message = response || validator.defaultMessage( element, "remote" );
errors[ element.name ] = previous.message = $.isFunction( message ) ? message( value ) : message;
validator.invalid[ element.name ] = true;
validator.showErrors( errors );
}
previous.valid = valid;
validator.stopRequest( element, valid );
}
}, param ) );
return "pending";
}
}
});
var pendingRequests = {},
ajax;
if ( $.ajaxPrefilter ) {
$.ajaxPrefilter(function( settings, _, xhr ) {
var port = settings.port;
if ( settings.mode === "abort" ) {
if ( pendingRequests[port] ) {
pendingRequests[port].abort();
}
pendingRequests[port] = xhr;
}
});
} else {
ajax = $.ajax;
$.ajax = function( settings ) {
var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,
port = ( "port" in settings ? settings : $.ajaxSettings ).port;
if ( mode === "abort" ) {
if ( pendingRequests[port] ) {
pendingRequests[port].abort();
}
pendingRequests[port] = ajax.apply(this, arguments);
return pendingRequests[port];
}
return ajax.apply(this, arguments);
};
}
}));// Magnific Popup v1.0.1 by Dmitry Semenov
// http://bit.ly/magnific-popup#build=inline+image+ajax+iframe+gallery+retina+imagezoom+fastclick
(function(a){typeof define=="function"&&define.amd?define(["jquery"],a):typeof exports=="object"?a(require("jquery")):a(window.jQuery||window.Zepto)})(function(a){var b="Close",c="BeforeClose",d="AfterClose",e="BeforeAppend",f="MarkupParse",g="Open",h="Change",i="mfp",j="."+i,k="mfp-ready",l="mfp-removing",m="mfp-prevent-close",n,o=function(){},p=!!window.jQuery,q,r=a(window),s,t,u,v,w=function(a,b){n.ev.on(i+a+j,b)},x=function(b,c,d,e){var f=document.createElement("div");return f.className="mfp-"+b,d&&(f.innerHTML=d),e?c&&c.appendChild(f):(f=a(f),c&&f.appendTo(c)),f},y=function(b,c){n.ev.triggerHandler(i+b,c),n.st.callbacks&&(b=b.charAt(0).toLowerCase()+b.slice(1),n.st.callbacks[b]&&n.st.callbacks[b].apply(n,a.isArray(c)?c:[c]))},z=function(b){if(b!==v||!n.currTemplate.closeBtn)n.currTemplate.closeBtn=a(n.st.closeMarkup.replace("%title%",n.st.tClose)),v=b;return n.currTemplate.closeBtn},A=function(){a.magnificPopup.instance||(n=new o,n.init(),a.magnificPopup.instance=n)},B=function(){var a=document.createElement("p").style,b=["ms","O","Moz","Webkit"];if(a.transition!==undefined)return!0;while(b.length)if(b.pop()+"Transition"in a)return!0;return!1};o.prototype={constructor:o,init:function(){var b=navigator.appVersion;n.isIE7=b.indexOf("MSIE 7.")!==-1,n.isIE8=b.indexOf("MSIE 8.")!==-1,n.isLowIE=n.isIE7||n.isIE8,n.isAndroid=/android/gi.test(b),n.isIOS=/iphone|ipad|ipod/gi.test(b),n.supportsTransition=B(),n.probablyMobile=n.isAndroid||n.isIOS||/(Opera Mini)|Kindle|webOS|BlackBerry|(Opera Mobi)|(Windows Phone)|IEMobile/i.test(navigator.userAgent),s=a(document),n.popupsCache={}},open:function(b){var c;if(b.isObj===!1){n.items=b.items.toArray(),n.index=0;var d=b.items,e;for(c=0;c(a||r.height())},_setFocus:function(){(n.st.focus?n.content.find(n.st.focus).eq(0):n.wrap).focus()},_onFocusIn:function(b){if(b.target!==n.wrap[0]&&!a.contains(n.wrap[0],b.target))return n._setFocus(),!1},_parseMarkup:function(b,c,d){var e;d.data&&(c=a.extend(d.data,c)),y(f,[b,c,d]),a.each(c,function(a,c){if(c===undefined||c===!1)return!0;e=a.split("_");if(e.length>1){var d=b.find(j+"-"+e[0]);if(d.length>0){var f=e[1];f==="replaceWith"?d[0]!==c[0]&&d.replaceWith(c):f==="img"?d.is("img")?d.attr("src",c):d.replaceWith(''):d.attr(e[1],c)}}else b.find(j+"-"+a).html(c)})},_getScrollbarSize:function(){if(n.scrollbarSize===undefined){var a=document.createElement("div");a.style.cssText="width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;",document.body.appendChild(a),n.scrollbarSize=a.offsetWidth-a.clientWidth,document.body.removeChild(a)}return n.scrollbarSize}},a.magnificPopup={instance:null,proto:o.prototype,modules:[],open:function(b,c){return A(),b?b=a.extend(!0,{},b):b={},b.isObj=!0,b.index=c||0,this.instance.open(b)},close:function(){return a.magnificPopup.instance&&a.magnificPopup.instance.close()},registerModule:function(b,c){c.options&&(a.magnificPopup.defaults[b]=c.options),a.extend(this.proto,c.proto),this.modules.push(b)},defaults:{disableOn:0,key:null,midClick:!1,mainClass:"",preloader:!0,focus:"",closeOnContentClick:!1,closeOnBgClick:!0,closeBtnInside:!0,showCloseBtn:!0,enableEscapeKey:!0,modal:!1,alignTop:!1,removalDelay:0,prependTo:null,fixedContentPos:"auto",fixedBgPos:"auto",overflowY:"auto",closeMarkup:'',tClose:"Close (Esc)",tLoading:"Loading...",autoFocusLast:!0}},a.fn.magnificPopup=function(b){A();var c=a(this);if(typeof b=="string")if(b==="open"){var d,e=p?c.data("magnificPopup"):c[0].magnificPopup,f=parseInt(arguments[1],10)||0;e.items?d=e.items[f]:(d=c,e.delegate&&(d=d.find(e.delegate)),d=d.eq(f)),n._openClick({mfpEl:d},c,e)}else n.isOpen&&n[b].apply(n,Array.prototype.slice.call(arguments,1));else b=a.extend(!0,{},b),p?c.data("magnificPopup",b):c[0].magnificPopup=b,n.addGroup(c,b);return c};var C="inline",D,E,F,G=function(){F&&(E.after(F.addClass(D)).detach(),F=null)};a.magnificPopup.registerModule(C,{options:{hiddenClass:"hide",markup:"",tNotFound:"Content not found"},proto:{initInline:function(){n.types.push(C),w(b+"."+C,function(){G()})},getInline:function(b,c){G();if(b.src){var d=n.st.inline,e=a(b.src);if(e.length){var f=e[0].parentNode;f&&f.tagName&&(E||(D=d.hiddenClass,E=x(D),D="mfp-"+D),F=e.after(E).detach().removeClass(D)),n.updateStatus("ready")}else n.updateStatus("error",d.tNotFound),e=a("
");return b.inlineElement=e,e}return n.updateStatus("ready"),n._parseMarkup(c,{},b),c}}});var H="ajax",I,J=function(){I&&a(document.body).removeClass(I)},K=function(){J(),n.req&&n.req.abort()};a.magnificPopup.registerModule(H,{options:{settings:null,cursor:"mfp-ajax-cur",tError:'The content could not be loaded.'},proto:{initAjax:function(){n.types.push(H),I=n.st.ajax.cursor,w(b+"."+H,K),w("BeforeChange."+H,K)},getAjax:function(b){I&&a(document.body).addClass(I),n.updateStatus("loading");var c=a.extend({url:b.src,success:function(c,d,e){var f={data:c,xhr:e};y("ParseAjax",f),n.appendContent(a(f.data),H),b.finished=!0,J(),n._setFocus(),setTimeout(function(){n.wrap.addClass(k)},16),n.updateStatus("ready"),y("AjaxContentAdded")},error:function(){J(),b.finished=b.loadError=!0,n.updateStatus("error",n.st.ajax.tError.replace("%url%",b.src))}},n.st.ajax.settings);return n.req=a.ajax(c),""}}});var L,M=function(b){if(b.data&&b.data.title!==undefined)return b.data.title;var c=n.st.image.titleSrc;if(c){if(a.isFunction(c))return c.call(n,b);if(b.el)return b.el.attr(c)||""}return""};a.magnificPopup.registerModule("image",{options:{markup:'
',cursor:"mfp-zoom-out-cur",titleSrc:"title",verticalFit:!0,tError:'The image could not be loaded.'},proto:{initImage:function(){var c=n.st.image,d=".image";n.types.push("image"),w(g+d,function(){n.currItem.type==="image"&&c.cursor&&a(document.body).addClass(c.cursor)}),w(b+d,function(){c.cursor&&a(document.body).removeClass(c.cursor),r.off("resize"+j)}),w("Resize"+d,n.resizeImage),n.isLowIE&&w("AfterChange",n.resizeImage)},resizeImage:function(){var a=n.currItem;if(!a||!a.img)return;if(n.st.image.verticalFit){var b=0;n.isLowIE&&(b=parseInt(a.img.css("padding-top"),10)+parseInt(a.img.css("padding-bottom"),10)),a.img.css("max-height",n.wH-b)}},_onImageHasSize:function(a){a.img&&(a.hasSize=!0,L&&clearInterval(L),a.isCheckingImgSize=!1,y("ImageHasSize",a),a.imgHidden&&(n.content&&n.content.removeClass("mfp-loading"),a.imgHidden=!1))},findImageSize:function(a){var b=0,c=a.img[0],d=function(e){L&&clearInterval(L),L=setInterval(function(){if(c.naturalWidth>0){n._onImageHasSize(a);return}b>200&&clearInterval(L),b++,b===3?d(10):b===40?d(50):b===100&&d(500)},e)};d(1)},getImage:function(b,c){var d=0,e=function(){b&&(b.img[0].complete?(b.img.off(".mfploader"),b===n.currItem&&(n._onImageHasSize(b),n.updateStatus("ready")),b.hasSize=!0,b.loaded=!0,y("ImageLoadComplete")):(d++,d<200?setTimeout(e,100):f()))},f=function(){b&&(b.img.off(".mfploader"),b===n.currItem&&(n._onImageHasSize(b),n.updateStatus("error",g.tError.replace("%url%",b.src))),b.hasSize=!0,b.loaded=!0,b.loadError=!0)},g=n.st.image,h=c.find(".mfp-img");if(h.length){var i=document.createElement("img");i.className="mfp-img",b.el&&b.el.find("img").length&&(i.alt=b.el.find("img").attr("alt")),b.img=a(i).on("load.mfploader",e).on("error.mfploader",f),i.src=b.src,h.is("img")&&(b.img=b.img.clone()),i=b.img[0],i.naturalWidth>0?b.hasSize=!0:i.width||(b.hasSize=!1)}return n._parseMarkup(c,{title:M(b),img_replaceWith:b.img},b),n.resizeImage(),b.hasSize?(L&&clearInterval(L),b.loadError?(c.addClass("mfp-loading"),n.updateStatus("error",g.tError.replace("%url%",b.src))):(c.removeClass("mfp-loading"),n.updateStatus("ready")),c):(n.updateStatus("loading"),b.loading=!0,b.hasSize||(b.imgHidden=!0,c.addClass("mfp-loading"),n.findImageSize(b)),c)}}});var N,O=function(){return N===undefined&&(N=document.createElement("p").style.MozTransform!==undefined),N};a.magnificPopup.registerModule("zoom",{options:{enabled:!1,easing:"ease-in-out",duration:300,opener:function(a){return a.is("img")?a:a.find("img")}},proto:{initZoom:function(){var a=n.st.zoom,d=".zoom",e;if(!a.enabled||!n.supportsTransition)return;var f=a.duration,g=function(b){var c=b.clone().removeAttr("style").removeAttr("class").addClass("mfp-animated-image"),d="all "+a.duration/1e3+"s "+a.easing,e={position:"fixed",zIndex:9999,left:0,top:0,"-webkit-backface-visibility":"hidden"},f="transition";return e["-webkit-"+f]=e["-moz-"+f]=e["-o-"+f]=e[f]=d,c.css(e),c},h=function(){n.content.css("visibility","visible")},i,j;w("BuildControls"+d,function(){if(n._allowZoom()){clearTimeout(i),n.content.css("visibility","hidden"),e=n._getItemToZoom();if(!e){h();return}j=g(e),j.css(n._getOffset()),n.wrap.append(j),i=setTimeout(function(){j.css(n._getOffset(!0)),i=setTimeout(function(){h(),setTimeout(function(){j.remove(),e=j=null,y("ZoomAnimationEnded")},16)},f)},16)}}),w(c+d,function(){if(n._allowZoom()){clearTimeout(i),n.st.removalDelay=f;if(!e){e=n._getItemToZoom();if(!e)return;j=g(e)}j.css(n._getOffset(!0)),n.wrap.append(j),n.content.css("visibility","hidden"),setTimeout(function(){j.css(n._getOffset())},16)}}),w(b+d,function(){n._allowZoom()&&(h(),j&&j.remove(),e=null)})},_allowZoom:function(){return n.currItem.type==="image"},_getItemToZoom:function(){return n.currItem.hasSize?n.currItem.img:!1},_getOffset:function(b){var c;b?c=n.currItem.img:c=n.st.zoom.opener(n.currItem.el||n.currItem);var d=c.offset(),e=parseInt(c.css("padding-top"),10),f=parseInt(c.css("padding-bottom"),10);d.top-=a(window).scrollTop()-e;var g={width:c.width(),height:(p?c.innerHeight():c[0].offsetHeight)-f-e};return O()?g["-moz-transform"]=g.transform="translate("+d.left+"px,"+d.top+"px)":(g.left=d.left,g.top=d.top),g}}});var P="iframe",Q="//about:blank",R=function(a){if(n.currTemplate[P]){var b=n.currTemplate[P].find("iframe");b.length&&(a||(b[0].src=Q),n.isIE8&&b.css("display",a?"block":"none"))}};a.magnificPopup.registerModule(P,{options:{markup:'
',srcAction:"iframe_src",patterns:{youtube:{index:"youtube.com",id:"v=",src:"//www.youtube.com/embed/%id%?autoplay=1"},vimeo:{index:"vimeo.com/",id:"/",src:"//player.vimeo.com/video/%id%?autoplay=1"},gmaps:{index:"//maps.google.",src:"%id%&output=embed"}}},proto:{initIframe:function(){n.types.push(P),w("BeforeChange",function(a,b,c){b!==c&&(b===P?R():c===P&&R(!0))}),w(b+"."+P,function(){R()})},getIframe:function(b,c){var d=b.src,e=n.st.iframe;a.each(e.patterns,function(){if(d.indexOf(this.index)>-1)return this.id&&(typeof this.id=="string"?d=d.substr(d.lastIndexOf(this.id)+this.id.length,d.length):d=this.id.call(this,d)),d=this.src.replace("%id%",d),!1});var f={};return e.srcAction&&(f[e.srcAction]=d),n._parseMarkup(c,f,b),n.updateStatus("ready"),c}}});var S=function(a){var b=n.items.length;return a>b-1?a-b:a<0?b+a:a},T=function(a,b,c){return a.replace(/%curr%/gi,b+1).replace(/%total%/gi,c)};a.magnificPopup.registerModule("gallery",{options:{enabled:!1,arrowMarkup:'',preload:[0,2],navigateByImgClick:!0,arrows:!0,tPrev:"Previous (Left arrow key)",tNext:"Next (Right arrow key)",tCounter:"%curr% of %total%"},proto:{initGallery:function(){var c=n.st.gallery,d=".mfp-gallery",e=Boolean(a.fn.mfpFastClick);n.direction=!0;if(!c||!c.enabled)return!1;u+=" mfp-gallery",w(g+d,function(){c.navigateByImgClick&&n.wrap.on("click"+d,".mfp-img",function(){if(n.items.length>1)return n.next(),!1}),s.on("keydown"+d,function(a){a.keyCode===37?n.prev():a.keyCode===39&&n.next()})}),w("UpdateStatus"+d,function(a,b){b.text&&(b.text=T(b.text,n.currItem.index,n.items.length))}),w(f+d,function(a,b,d,e){var f=n.items.length;d.counter=f>1?T(c.tCounter,e.index,f):""}),w("BuildControls"+d,function(){if(n.items.length>1&&c.arrows&&!n.arrowLeft){var b=c.arrowMarkup,d=n.arrowLeft=a(b.replace(/%title%/gi,c.tPrev).replace(/%dir%/gi,"left")).addClass(m),f=n.arrowRight=a(b.replace(/%title%/gi,c.tNext).replace(/%dir%/gi,"right")).addClass(m),g=e?"mfpFastClick":"click";d[g](function(){n.prev()}),f[g](function(){n.next()}),n.isIE7&&(x("b",d[0],!1,!0),x("a",d[0],!1,!0),x("b",f[0],!1,!0),x("a",f[0],!1,!0)),n.container.append(d.add(f))}}),w(h+d,function(){n._preloadTimeout&&clearTimeout(n._preloadTimeout),n._preloadTimeout=setTimeout(function(){n.preloadNearbyImages(),n._preloadTimeout=null},16)}),w(b+d,function(){s.off(d),n.wrap.off("click"+d),n.arrowLeft&&e&&n.arrowLeft.add(n.arrowRight).destroyMfpFastClick(),n.arrowRight=n.arrowLeft=null})},next:function(){n.direction=!0,n.index=S(n.index+1),n.updateItemHTML()},prev:function(){n.direction=!1,n.index=S(n.index-1),n.updateItemHTML()},goTo:function(a){n.direction=a>=n.index,n.index=a,n.updateItemHTML()},preloadNearbyImages:function(){var a=n.st.gallery.preload,b=Math.min(a[0],n.items.length),c=Math.min(a[1],n.items.length),d;for(d=1;d<=(n.direction?c:b);d++)n._preloadItem(n.index+d);for(d=1;d<=(n.direction?b:c);d++)n._preloadItem(n.index-d)},_preloadItem:function(b){b=S(b);if(n.items[b].preloaded)return;var c=n.items[b];c.parsed||(c=n.parseEl(b)),y("LazyLoad",c),c.type==="image"&&(c.img=a('').on("load.mfploader",function(){c.hasSize=!0}).on("error.mfploader",function(){c.hasSize=!0,c.loadError=!0,y("LazyLoadError",c)}).attr("src",c.src)),c.preloaded=!0}}});var U="retina";a.magnificPopup.registerModule(U,{options:{replaceSrc:function(a){return a.src.replace(/\.\w+$/,function(a){return"@2x"+a})},ratio:1},proto:{initRetina:function(){if(window.devicePixelRatio>1){var a=n.st.retina,b=a.ratio;b=isNaN(b)?b():b,b>1&&(w("ImageHasSize."+U,function(a,c){c.img.css({"max-width":c.img[0].naturalWidth/b,width:"100%"})}),w("ElementParse."+U,function(c,d){d.src=a.replaceSrc(d,b)}))}}}}),function(){var b=1e3,c="ontouchstart"in window,d=function(){r.off("touchmove"+f+" touchend"+f)},e="mfpFastClick",f="."+e;a.fn.mfpFastClick=function(e){return a(this).each(function(){var g=a(this),h;if(c){var i,j,k,l,m,n;g.on("touchstart"+f,function(a){l=!1,n=1,m=a.originalEvent?a.originalEvent.touches[0]:a.touches[0],j=m.clientX,k=m.clientY,r.on("touchmove"+f,function(a){m=a.originalEvent?a.originalEvent.touches:a.touches,n=m.length,m=m[0];if(Math.abs(m.clientX-j)>10||Math.abs(m.clientY-k)>10)l=!0,d()}).on("touchend"+f,function(a){d();if(l||n>1)return;h=!0,a.preventDefault(),clearTimeout(i),i=setTimeout(function(){h=!1},b),e()})})}g.on("click"+f,function(){h||e()})})},a.fn.destroyMfpFastClick=function(){a(this).off("touchstart"+f+" click"+f),c&&r.off("touchmove"+f+" touchend"+f)}}(),A()})/**
* Documentations: https://github.com/verlok/lazyload
*
* LazyLoad Note - The universal, recommended version of LazyLoad is 8.x since it supports ALL browsers
* from IE9 up. Starting from version 9, LazyLoad uses the IntersectionObserver API, which
* is not supported by Internet Explorer and Safari (yet). As a result, if you included the
* latest version of LazyLoad, all the images would be loaded at once in those browsers.
*
* SITE123 Note - We had an issue at old browsers (also mobile browsers) that
* all our website stop load images & content because we use the newest LazyLoad
* version (the content didn't appear because there was a JS error).
* Because we are using a compress JS we was unable to include there versions in
* the way they did in there example, so we change it a little to load the correct
* LazyLoad version related to the user browser.
*
* Source:
* (function(w, d){
* var b = d.getElementsByTagName('body')[0];
* var s = d.createElement("script"); s.async = true;
* var v = !("IntersectionObserver" in w) ? "8.7.1" : "10.5.2";
* s.src = "https://cdnjs.cloudflare.com/ajax/libs/vanilla-lazyload/" + v + "/lazyload.min.js";
* w.lazyLoadOptions = {}; // Your options here. See "recipes" for more information about async.
* b.appendChild(s);
* }(window, document));
*/
function LazyLoad_Loader( w, d ) {
//
var v = !("IntersectionObserver" in w) ? "8.7.1" : "10.5.2";
// include the correct LazyLoad version related to the user browser
if ( v === '10.5.2' ) {
w._extends=Object.assign||function(e){for(var t=1;t-1&&(v(e,t),u(e,t.class_loading)),a(e,t),n(e,"was-processed",!0),f(t.callback_set,e)},p=function(e){return e.isIntersecting||e.intersectionRatio>0},h=function(t,n){this._settings=e(t),this._setObserver(),this.update(n)};h.prototype={_setObserver:function(){var e=this;if(c){var t=this._settings,n={root:t.container===document?null:t.container,rootMargin:t.threshold+"px"};this._observer=new IntersectionObserver(function(t){t.forEach(function(t){if(p(t)){var n=t.target;b(n,e._settings),e._observer.unobserve(n)}}),e._elements=r(e._elements)},n)}},update:function(e){var t=this,n=this._settings,s=e||n.container.querySelectorAll(n.elements_selector);this._elements=r(Array.prototype.slice.call(s)),this._observer?this._elements.forEach(function(e){t._observer.observe(e)}):(this._elements.forEach(function(e){b(e,n)}),this._elements=r(this._elements))},destroy:function(){var e=this;this._observer&&(r(this._elements).forEach(function(t){e._observer.unobserve(t)}),this._observer=null),this._elements=null,this._settings=null}};var y=window.lazyLoadOptions;return i&&y&&function(e,t){if(t.length)for(var n,r=0;n=t[r];r+=1)s(e,n);else s(e,t)}(h,y),h});
} else {
w._extends=Object.assign||function(e){for(var t=1;t=o(e)+n+e.offsetHeight},a=function(e,t,n){return(t===window?window.pageXOffset:s(t))>=s(e)+n+e.offsetWidth},c=function(e,t,n){return!(i(e,t,n)||l(e,t,n)||r(e,t,n)||a(e,t,n))},u=function(e,t){var n,o=new e(t);try{n=new CustomEvent("LazyLoad::Initialized",{detail:{instance:o}})}catch(e){(n=document.createEvent("CustomEvent")).initCustomEvent("LazyLoad::Initialized",!1,!1,{instance:o})}window.dispatchEvent(n)},d=function(e,t){return e.getAttribute("data-"+t)},h=function(e,t,n){return e.setAttribute("data-"+t,n)},f=function(e,t){var n=e.parentNode;if(!n||"PICTURE"===n.tagName)for(var o=0;o0;)e.splice(o.pop(),1)},_startScrollHandler:function(){this._isHandlingScroll||(this._isHandlingScroll=!0,this._settings.container.addEventListener("scroll",this._boundHandleScroll))},_stopScrollHandler:function(){this._isHandlingScroll&&(this._isHandlingScroll=!1,this._settings.container.removeEventListener("scroll",this._boundHandleScroll))},handleScroll:function(){var e=this._settings.throttle;if(0!==e){var t=Date.now(),n=e-(t-this._previousLoopTime);n<=0||n>e?(this._loopTimeout&&(clearTimeout(this._loopTimeout),this._loopTimeout=null),this._previousLoopTime=t,this._loopThroughElements()):this._loopTimeout||(this._loopTimeout=setTimeout(function(){this._previousLoopTime=Date.now(),this._loopTimeout=null,this._loopThroughElements()}.bind(this),n))}else this._loopThroughElements()},update:function(){this._elements=Array.prototype.slice.call(this._queryOriginNode.querySelectorAll(this._settings.elements_selector)),this._purgeElements(),this._loopThroughElements(),this._startScrollHandler()},destroy:function(){window.removeEventListener("resize",this._boundHandleScroll),this._loopTimeout&&(clearTimeout(this._loopTimeout),this._loopTimeout=null),this._stopScrollHandler(),this._elements=null,this._queryOriginNode=null,this._settings=null}};var b=window.lazyLoadOptions;return p&&b&&function(e,t){var n=t.length;if(n)for(var o=0;o').prependTo('body');
// SITE123 - We add this to detect when the Parallax is active
if ( !$('html').hasClass('parallax-disabled') ) $('html').addClass('parallax-active');
var slider = this.$element.find('>.parallax-slider');
var sliderExisted = false;
if (slider.length == 0)
this.$slider = $('').prependTo(this.$mirror);
else {
this.$slider = slider.prependTo(this.$mirror)
sliderExisted = true;
}
this.$mirror.addClass('parallax-mirror').css({
visibility: 'hidden',
zIndex: this.zIndex,
position: 'fixed',
top: 0,
left: 0,
overflow: 'hidden',
backgroundColor: this.backgroundcolor
}).attr('id',this.idele);
this.$slider.addClass('parallax-slider').one('load', function() {
if (!self.naturalHeight || !self.naturalWidth) {
self.naturalHeight = this.naturalHeight || this.height || 1;
self.naturalWidth = this.naturalWidth || this.width || 1;
}
self.aspectRatio = self.naturalWidth / self.naturalHeight;
Parallax.isSetup || Parallax.setup();
Parallax.sliders.push(self);
Parallax.isFresh = false;
Parallax.requestRender();
});
// Add opacity to the image
this.$slider.css('opacity',this.opacity);
// Add filter to the image
this.$slider.css('filter',this.filter);
if (!sliderExisted)
this.$slider[0].src = this.imageSrc;
if (this.naturalHeight && this.naturalWidth || this.$slider[0].complete || slider.length > 0) {
this.$slider.trigger('load');
}
};
// Parallax Instance Methods
$.extend(Parallax.prototype, {
speed: 0.2,
bleed: 0,
zIndex: -100,
opacity: 1,
filter: '',
backgroundcolor: '#ffffff',
idele: '',
iosFix: true,
androidFix: true,
position: 'center',
overScrollFix: false,
refresh: function() {
this.boxWidth = this.$element.outerWidth();
this.boxHeight = this.$element.outerHeight() + this.bleed * 1; //We changed 2 to 1 so only the header will be fixed (without bottom)
this.boxOffsetTop = this.$element.offset().top - this.bleed;
this.boxOffsetLeft = this.$element.offset().left;
this.boxOffsetBottom = this.boxOffsetTop + this.boxHeight;
/**
* Chrome + RTL + Iframe Issue - Chrome have an issue with RTL iframes, the
* scrollbar place at the left side instead on the right side. Because of that behavior
* the browser calculate the element left position including the Scrollbar Width and we
* must decrease it so the Parallax will fit.
* Note: its not an issue with `this.$element.offset().left` you can use also
* `getBoundingClientRect() ` to see that the bug is related to Chrome only.
*/
var chrome_box_bugfix = this;
(function () {
// we are not using RTL so there is no issue
if ( $('html').attr('dir') !== 'rtl' ) return;
// we are not in Iframe so the scrollbar is at the correct place
if ( !window.frameElement ) return;
// we are not using chrome browser so there is no issue
if ( !isChromium() ) return;
// decrease he scrollbar width from the box offset left
chrome_box_bugfix.boxOffsetLeft -= Parallax_getScrollbarWidth();
/* https://stackoverflow.com/questions/13382516/getting-scroll-bar-width-using-javascript */
function Parallax_getScrollbarWidth() {
if ($(document).height() > $(window).height()) { //Make sure this page have a scroll
var outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.width = "100px";
outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps
document.body.appendChild(outer);
var widthNoScroll = outer.offsetWidth;
// force scrollbars
outer.style.overflow = "scroll";
// add innerdiv
var inner = document.createElement("div");
inner.style.width = "100%";
outer.appendChild(inner);
var widthWithScroll = inner.offsetWidth;
// remove divs
outer.parentNode.removeChild(outer);
return widthNoScroll - widthWithScroll;
} else {
return 0; //If this page is short without a scroll we don't add padding
}
}
/**
* The function check if the current user browser id Chrome.
* Source: https://stackoverflow.com/a/13348618/469161
*/
function isChromium() {
var isChromium = window.chrome,
winNav = window.navigator,
vendorName = winNav.vendor,
isOpera = winNav.userAgent.indexOf("OPR") > -1,
isIEedge = winNav.userAgent.indexOf("Edge") > -1,
isIOSChrome = winNav.userAgent.match("CriOS");
if (isIOSChrome) {
// is Google Chrome on IOS
return true;
} else if (
isChromium !== null &&
typeof isChromium !== "undefined" &&
vendorName === "Google Inc." &&
isOpera === false &&
isIEedge === false
) {
// is Google Chrome
return true;
} else {
// not Google Chrome
return false;
}
}
})();
var winHeight = Parallax.winHeight;
var docHeight = Parallax.docHeight;
var maxOffset = Math.min(this.boxOffsetTop, docHeight - winHeight);
var minOffset = Math.max(this.boxOffsetTop + this.boxHeight - winHeight, 0);
var imageHeightMin = this.boxHeight + (maxOffset - minOffset) * (1 - this.speed) | 0;
var imageOffsetMin = (this.boxOffsetTop - maxOffset) * (1 - this.speed) | 0;
if (imageHeightMin * this.aspectRatio >= this.boxWidth) {
this.imageWidth = imageHeightMin * this.aspectRatio | 0;
this.imageHeight = imageHeightMin;
this.offsetBaseTop = imageOffsetMin;
var margin = this.imageWidth - this.boxWidth;
if (this.positionX == 'left') {
this.offsetLeft = 0;
} else if (this.positionX == 'right') {
this.offsetLeft = - margin;
} else if (!isNaN(this.positionX)) {
this.offsetLeft = Math.max(this.positionX, - margin);
} else {
this.offsetLeft = - margin / 2 | 0;
}
} else {
this.imageWidth = this.boxWidth;
this.imageHeight = this.boxWidth / this.aspectRatio | 0;
this.offsetLeft = 0;
var margin = this.imageHeight - imageHeightMin;
if (this.positionY == 'top') {
this.offsetBaseTop = imageOffsetMin;
} else if (this.positionY == 'bottom') {
this.offsetBaseTop = imageOffsetMin - margin;
} else if (!isNaN(this.positionY)) {
this.offsetBaseTop = imageOffsetMin + Math.max(this.positionY, - margin);
} else {
this.offsetBaseTop = imageOffsetMin - margin / 2 | 0;
}
}
},
render: function() {
var scrollTop = Parallax.scrollTop;
var scrollLeft = Parallax.scrollLeft;
var overScroll = this.overScrollFix ? Parallax.overScroll : 0;
var scrollBottom = scrollTop + Parallax.winHeight;
if (this.boxOffsetBottom > scrollTop && this.boxOffsetTop <= scrollBottom) {
this.visibility = 'visible';
this.mirrorTop = this.boxOffsetTop - scrollTop;
this.mirrorLeft = this.boxOffsetLeft - scrollLeft;
this.offsetTop = this.offsetBaseTop - this.mirrorTop * (1 - this.speed);
} else {
this.visibility = 'hidden';
}
this.$mirror.css({
transform: 'translate3d(0px, 0px, 0px)',
visibility: this.visibility,
top: this.mirrorTop - overScroll,
left: this.mirrorLeft,
height: this.boxHeight,
width: this.boxWidth
});
this.$slider.css({
transform: 'translate3d(0px, 0px, 0px)',
position: 'absolute',
top: this.offsetTop,
left: this.offsetLeft,
height: this.imageHeight,
width: this.imageWidth,
maxWidth: 'none'
});
}
});
// Parallax Static Methods
$.extend(Parallax, {
scrollTop: 0,
scrollLeft: 0,
winHeight: 0,
winWidth: 0,
docHeight: 1 << 30,
docWidth: 1 << 30,
sliders: [],
isReady: false,
isFresh: false,
isBusy: false,
setup: function() {
if (this.isReady) return;
var $doc = $(document), $win = $(window);
var loadDimensions = function() {
Parallax.winHeight = $win.height();
Parallax.winWidth = $win.width();
Parallax.docHeight = $doc.height();
Parallax.docWidth = $doc.width();
};
var loadScrollPosition = function() {
var winScrollTop = $win.scrollTop();
var scrollTopMax = Parallax.docHeight - Parallax.winHeight;
var scrollLeftMax = Parallax.docWidth - Parallax.winWidth;
Parallax.scrollTop = Math.max(0, Math.min(scrollTopMax, winScrollTop));
Parallax.scrollLeft = Math.max(0, Math.min(scrollLeftMax, $win.scrollLeft()));
Parallax.overScroll = Math.max(winScrollTop - scrollTopMax, Math.min(winScrollTop, 0));
};
$win.on('resize.px.parallax load.px.parallax', function() {
loadDimensions();
Parallax.isFresh = false;
Parallax.requestRender();
})
.on('scroll.px.parallax load.px.parallax', function() {
loadScrollPosition();
Parallax.requestRender();
});
loadDimensions();
loadScrollPosition();
this.isReady = true;
},
configure: function(options) {
if (typeof options == 'object') {
delete options.refresh;
delete options.render;
$.extend(this.prototype, options);
}
},
refresh: function() {
$.each(this.sliders, function(){ this.refresh() });
this.isFresh = true;
},
render: function() {
this.isFresh || this.refresh();
$.each(this.sliders, function(){ this.render() });
},
requestRender: function() {
var self = this;
if (!this.isBusy) {
this.isBusy = true;
window.requestAnimationFrame(function() {
self.render();
self.isBusy = false;
});
}
},
destroy: function(el){
var i,
parallaxElement = $(el).data('px.parallax');
parallaxElement.$mirror.remove();
for(i=0; i < this.sliders.length; i+=1){
if(this.sliders[i] == parallaxElement){
this.sliders.splice(i, 1);
}
}
$(el).data('px.parallax', false);
if(this.sliders.length === 0){
$(window).off('scroll.px.parallax resize.px.parallax load.px.parallax');
this.isReady = false;
Parallax.isSetup = false;
}
}
});
// Parallax Plugin Definition
function Plugin(option) {
return this.each(function () {
var $this = $(this);
var options = typeof option == 'object' && option;
if (this == window || this == document || $this.is('body')) {
Parallax.configure(options);
}
else if (!$this.data('px.parallax')) {
options = $.extend({}, $this.data(), options);
$this.data('px.parallax', new Parallax(this, options));
}
else if (typeof option == 'object')
{
$.extend($this.data('px.parallax'), options);
}
if (typeof option == 'string') {
if(option == 'destroy'){
Parallax['destroy'](this);
}else{
Parallax[option]();
}
}
})
};
var old = $.fn.parallax;
$.fn.parallax = Plugin;
$.fn.parallax.Constructor = Parallax;
// Parallax No Conflict
$.fn.parallax.noConflict = function () {
$.fn.parallax = old;
return this;
};
// Parallax Data-API
$(document).on('ready.px.parallax.data-api', function () {
$('[data-parallax="scroll"]').parallax();
});
}(jQuery, window, document));
/*!
Zoom 1.7.18
license: MIT
http://www.jacklmoore.com/zoom
*/
(function(o){var t={url:!1,callback:!1,target:!1,duration:120,on:"mouseover",touch:!0,onZoomIn:!1,onZoomOut:!1,magnify:1};o.zoom=function(t,n,e,i){var u,c,a,r,m,l,s,f=o(t),h=f.css("position"),d=o(n);return t.style.position=/(absolute|fixed)/.test(h)?h:"relative",t.style.overflow="hidden",e.style.width=e.style.height="",o(e).addClass("zoomImg").css({position:"absolute",top:0,left:0,opacity:0,width:e.width*i,height:e.height*i,border:"none",maxWidth:"none",maxHeight:"none"}).appendTo(t),{init:function(){c=f.outerWidth(),u=f.outerHeight(),n===t?(r=c,a=u):(r=d.outerWidth(),a=d.outerHeight()),m=(e.width-c)/r,l=(e.height-u)/a,s=d.offset()},move:function(o){var t=o.pageX-s.left,n=o.pageY-s.top;n=Math.max(Math.min(n,a),0),t=Math.max(Math.min(t,r),0),e.style.left=t*-m+"px",e.style.top=n*-l+"px"}}},o.fn.zoom=function(n){return this.each(function(){var e=o.extend({},t,n||{}),i=e.target&&o(e.target)[0]||this,u=this,c=o(u),a=document.createElement("img"),r=o(a),m="mousemove.zoom",l=!1,s=!1;if(!e.url){var f=u.querySelector("img");if(f&&(e.url=f.getAttribute("data-src")||f.currentSrc||f.src),!e.url)return}c.one("zoom.destroy",function(o,t){c.off(".zoom"),i.style.position=o,i.style.overflow=t,a.onload=null,r.remove()}.bind(this,i.style.position,i.style.overflow)),a.onload=function(){function t(t){f.init(),f.move(t),r.stop().fadeTo(o.support.opacity?e.duration:0,1,o.isFunction(e.onZoomIn)?e.onZoomIn.call(a):!1)}function n(){r.stop().fadeTo(e.duration,0,o.isFunction(e.onZoomOut)?e.onZoomOut.call(a):!1)}var f=o.zoom(i,u,a,e.magnify);"grab"===e.on?c.on("mousedown.zoom",function(e){1===e.which&&(o(document).one("mouseup.zoom",function(){n(),o(document).off(m,f.move)}),t(e),o(document).on(m,f.move),e.preventDefault())}):"click"===e.on?c.on("click.zoom",function(e){return l?void 0:(l=!0,t(e),o(document).on(m,f.move),o(document).one("click.zoom",function(){n(),l=!1,o(document).off(m,f.move)}),!1)}):"toggle"===e.on?c.on("click.zoom",function(o){l?n():t(o),l=!l}):"mouseover"===e.on&&(f.init(),c.on("mouseenter.zoom",t).on("mouseleave.zoom",n).on(m,f.move)),e.touch&&c.on("touchstart.zoom",function(o){o.preventDefault(),s?(s=!1,n()):(s=!0,t(o.originalEvent.touches[0]||o.originalEvent.changedTouches[0]))}).on("touchmove.zoom",function(o){o.preventDefault(),f.move(o.originalEvent.touches[0]||o.originalEvent.changedTouches[0])}).on("touchend.zoom",function(o){o.preventDefault(),s&&(s=!1,n())}),o.isFunction(e.callback)&&e.callback.call(a)},a.src=e.url})},o.fn.zoom.defaults=t})(window.jQuery);//Run when the page load (before images and other resource)
jQuery(function($) {
$( document ).on( 's123.page.ready', function( event ) {
var $section = $('.s123-module-restaurantReservation.layout-1');
$section.each(function( index ) {
var $sectionThis = $(this);
(function() {
googleMapPopUp.init({
locationData : $sectionThis.find('.mapPopupActivator'),
mapsDisplayDomain : $GLOBALS["maps-display-domain"],
longFreeCustomer : longFreeCustomer,
language : languageCode
});
})();
if ( $sectionThis.find(".restaurantWorkingDays").length == 0) return;
var rr = JSON.parse($sectionThis.find(".restaurantWorkingDays").val());
/**
* Check if the days are inactive
* If they are inactive hide the calendar and show the message
*/
var inActiveDays = 0;
$.each(rr.businessHours,function( index, dayOfWeek) {
if (!dayOfWeek.isActive) {
inActiveDays ++;
}
});
if (inActiveDays == 7 && rr.fullTime == '') {
$sectionThis.find('.note-container').removeClass('hidden');
$sectionThis.find('.calendar-container').addClass('hidden');
}
buisnessHoursTemplate.init({
$buisnessHourContainer : $sectionThis.find('.businessWorkingDays'),
buisnessHourJSON : $sectionThis.find(".restaurantWorkingDays")
});
/*
* Determinate if the business is active every day after 24:00
* if it is then move the hours after 24:00 to the next day and close the rest of the shifts
*/
if ( rr.fullTime.length == 0 ) {
$.each(rr.businessHours, function( index, day ) {
var startShift = 'startTime3';
var endShift = 'endTime3';
if ( day.startTime3 == '' || day.endTime3 == '') {
startShift = 'startTime2';
endShift = 'endTime2';
}
if ( day.startTime2 == '' || day.endTime2 == '') {
startShift = 'startTime1';
endShift = 'endTime1';
}
var startHour = parseInt(day[startShift].substring(0,2));
var startMin = day[startShift].substring(3,5);
var endHour = parseInt(day[endShift].substring(0,2));
var endMin = day[endShift].substring(3,5);
if ( endHour <= startHour ) {
rr.businessHours[index][endShift] = '23:59';
var dayIndex = (index+1);
if (index == 6) {
dayIndex = 0;
}
if ( endHour < 10) endHour = '0'+endHour.toString();
rr.businessHours[dayIndex].startTime0 = '00:'+ startMin;
rr.businessHours[dayIndex].endTime0 = endHour + ':' + endMin;
if ( !rr.businessHours[dayIndex].isActive ) {
rr.businessHours[dayIndex].isActive = true;
rr.businessHours[dayIndex].startTime1 = '';
rr.businessHours[dayIndex].endTime1 = '';
rr.businessHours[dayIndex].startTime2 = '';
rr.businessHours[dayIndex].endTime2 = '';
rr.businessHours[dayIndex].startTime3 = '';
rr.businessHours[dayIndex].endTime3 = '';
}
}
});
}
/*
* If the 24/7 is not active the determinate what days are active and if found that the day is not active then
* add to the string 'disabledDays'
*/
var disabledDays ="";
if (rr.fullTime == 'on') {
$.each(rr.businessHours,function( index, weekday ) {
weekday.isActive = true;
weekday.startTime1 ='00:00';
weekday.endTime1 ='24:00';
weekday.startTime2 ='';
weekday.endTime2 ='';
weekday.startTime3 ='';
weekday.endTime3 ='';
});
} else {
var total = rr.businessHours.length;
$.each(rr.businessHours, function( index ) {
if ( !rr.businessHours[index].isActive ) {
if (rr.firstDayOfWeek == '0') {
disabledDays += index;
} else {
disabledDays += (index + 1) % 7;
}
if ( index < ( total-1 ) ) {
disabledDays += ',';
}
}
});
}
var datePickerFormat = rr.dateFormat;
if (rr.dateFormat == 'd/m/Y') {
datePickerFormat = 'dd/mm/yyyy';
} else {
datePickerFormat = 'mm/dd/yyyy';
}
var calendarStartTime = $sectionThis.find('.clientTimeByZone').val();
var calendar = new calendar_handler();
var $datepicker = $sectionThis.find('.sandbox-container .fake-input.r-s-datePicker');
var $hiddenInput = $sectionThis.find('[data-id="'+$datepicker.data('related-id')+'"]');
var $restaurantDatesContainer = $sectionThis.find('.restaurantDatesContainer');
var $restaurantTableHourContainer = $sectionThis.find('.restaurantTableHourContainer');
if ( $restaurantTableHourContainer.find('.table-hour').length == 0) {
$restaurantTableHourContainer.append('');
}
var $tableHour = $restaurantTableHourContainer.find('.table-hour');
$datepicker.on('changeDate', function() {
var $this = $(this);
$tableHour.empty();
buildHourSelect(rr, $this.parent(), $restaurantDatesContainer, $tableHour);
if ( $tableHour.text().length <=0 ) {
$tableHour.addClass('hidden');
$restaurantTableHourContainer.find('.no-time-available').removeClass('hidden');
$sectionThis.find('.makeOrder').attr('disabled',true);
} else {
$restaurantTableHourContainer.find('.no-time-available').addClass('hidden');
$tableHour.removeClass('hidden');
$sectionThis.find('.makeOrder').attr('disabled',false);
}
});
$sectionThis.find('.makeOrder').click(function() {
var $emailIcon = $(this);
var websiteID = $sectionThis.find('.websiteID').val();
var moduleID = $sectionThis.find('.moduleID').val();
var w = $('#w').val();
var clientTime = calendarStartTime.substring(0,10);
var autoConfirm = $sectionThis.find('.confirmationStyle').val();
var tableSize = $sectionThis.find('.tableSize').val();
var tableHour = $sectionThis.find('.table-hour').val();
tableHour = changeTimeFormat(rr.timeFormat,tableHour);
var tableDate = $sectionThis.find('.restaurantDatesContainer input').val();
buildPopup('popupRestaurantReservations','',
buildRestaurantReservationForm(w,websiteID,moduleID,tableDate,tableSize,tableHour,clientTime,autoConfirm),'',true,false,true,'','');
$('#popupRestaurantReservations').find('.restaurantReservationsFormPopup').each( function( index ) {
var $form = $(this);
/**
* jQuery Validation Plugin Initial
* Documentation : http://jqueryvalidation.org/documentation/
*/
$form.validate({
errorElement: 'div',
errorClass: 'help-block',
focusInvalid: true,
ignore: "",
highlight: function (e) {
$(e).closest('.form-group').removeClass('has-info').addClass('has-error');
},
success: function (e) {
$(e).closest('.form-group').removeClass('has-error');
$(e).remove();
},
submitHandler: function( form ) {
var $form = $(form);
$form.find('button:submit').prop('disabled', true);
$.ajax({
type: "POST",
url: "/versions/"+$('#versionNUM').val()+"/include/restaurantReservationsO.php",
data: $form.serialize(),
success: function( data ) {
$form.trigger("reset");
$form.addClass("hidden");
$(".orderConfirmation").find(".orderId").text(JSON.parse(data).orderID);
$(".orderConfirmation").removeClass("hidden");
$form.next().find(".close-order-thank-you").on("click",function() {
buildPopup_CloseAction('popupRestaurantReservations');
$form.find(".tableSize,.table-hour").find("option:first-child").attr('selected','selected');
$sectionThis.find('.restaurantReservationsForm').get(0).reset();
calendar.setDate(new Date(calendarStartTime));
$datepicker.trigger('changeDate');
});
if (autoConfirm == "1")
$form.next().find(".thankYouMessage").text(translations.ThankYouAuto+"!");
$form.find('button:submit').prop('disabled', false);
WizardNotificationUpdate();
}
});
return false;
}
});
});
});
calendar.init({
$fakeInput: $datepicker,
$hiddenInput: $hiddenInput,
type: 'datePicker',
title: translations.chooseDate,
calendarSettings: {
format: $datepicker.data('date-format'),
weekStart: parseInt(rr.firstDayOfWeek),
todayBtn: "linked",
clearBtn: false,
language: "en",
startDate: new Date(calendarStartTime).toString(),
daysOfWeekDisabled: disabledDays,
todayHighlight: true
},
onSubmit: function( selectedDate ) {
$datepicker.html(selectedDate);
$hiddenInput.val(selectedDate);
$datepicker.trigger('changeDate');
},
onInit: function() {
$datepicker.trigger('changeDate');
}
});
});
});
});
function changeTimeFormat( websiteTimeFormat, time ) {
switch( websiteTimeFormat ) {
case 'H:i':
return moment(time,"hmm").format("HH:mm");
break;
case 'h:i A':
return moment(time,"hmm").format("hh:mm A");
break;
}
}
function changeDateFormat( websiteDateFormat, date ) {
switch( websiteDateFormat ) {
case 'YYYY-mm-DD m/d/Y':
return moment(date,"mm DD YYYY").format("YYYY-mm-DD");
break;
case 'YYYY-mm-DD d/m/Y':
return moment(date,"DD mm YYYY").format("YYYY-mm-DD");
break;
}
}
function buildHourSelect( rr, $this, $restaurantDatesContainer, $tableHour ) {
var dateValue = $this.find('input').val();
if ( !dateValue ) throw 'Missing date parameter';
dateValue = changeDateFormat( 'YYYY-mm-DD '+ rr.dateFormat, dateValue );
for( var i = 0 ; i <= 3 ; i++ ) {
/*
* addShift is a boolean variable that determinate if it's the second or third shift
* if it's the first shift then set it to false the rest should be on true this way
* the hours the function 'buildHourSelect' will add the new hours to the first shift
*/
var addShift = false;
if ( i > 1 ) {
addShift = true ;
}
var dayOfWeek = new Date(dateValue).getDay();
if ( dayOfWeek == 0) {
if ( parseInt(rr.firstDayOfWeek) == 1 ) {
var dataIndex = 6;
} else {
var dataIndex = dayOfWeek;
}
} else {
var dataIndex = dayOfWeek - parseInt(rr.firstDayOfWeek);
}
var startTime = 'startTime'+i;
var endTime = 'endTime'+i;
startTime = rr.businessHours[dataIndex][startTime];
endTime = rr.businessHours[dataIndex][endTime];
if (startTime == ''|| endTime == '' || !rr.businessHours[dataIndex].isActive)
continue;
var selectedDate = new Date(dateValue);
if ( getDateFormat(selectedDate) == getDateFormat(new Date()) && new Date().getTime() >= moment(dateValue+" "+startTime).valueOf()) {
startTime = moment(dateValue+" "+$restaurantDatesContainer.data('corrent-time')).valueOf();
} else {
startTime = moment(dateValue+" "+startTime).valueOf();
}
endTime = moment(dateValue+" "+endTime).valueOf();
for ( ;startTime < endTime ; startTime += 900000 ) {
var newdate = new Date(startTime);
var newHour = newdate.getHours();
var newMinutes = newdate.getMinutes();
if (newHour.toString().length == 1 )
newHour = '0' + newHour;
if (newMinutes.toString().length == 1 )
newMinutes = '0' + newMinutes;
/*
* Prevent duplicated time because the customer can start second shift or third shift
* from the same time for example shift 1 is 08:00-12:00 and shift 2 from 12:00-16:00
* the 12:00 will be shown only 1 time
**/
var hourExists = false;
$.each($tableHour.find('option'),function(index) {
$optionVal = $(this).val();
if ($optionVal == newHour+':'+newMinutes) {
hourExists = true;
return false;
}
});
if (!hourExists) $tableHour.append('');
else continue;
}
}
}
function getDateFormat( DateChoosed ) {
var formattedDate = DateChoosed;
return formattedDate.getFullYear() +'-'+ (formattedDate.getMonth() + 1) + '-'+ formattedDate.getDate();
}
function getAnotherDateFormat( DateChoosed ) {
var formattedDate = DateChoosed;
return (formattedDate.getMonth() + 1) +'/'+ formattedDate.getDate()+'/'+ formattedDate.getFullYear();
}
/**
* The function build the html of the order and order confirmation form
*
* @param {string} websiteID - Website ID.
* @param {string} moduleID - Module ID.
* @param {string} uniqueID - Unique item ID.
* @return {string} html - Html of the form.
*/
function buildRestaurantReservationForm( w, websiteID, moduleID, tableDate, tableSize, tableHour,clientTime, autoConfirm) {
var html = '';
html += '';
html +='
';
html += '
';
html += '
';
html += '
';
html += '';
html += '
';
html += '
';
html += '
';
html += '
';
html += '
';
html += '
';
html += ' ';
html += '';
html += '
';
html += '
';
html += '
';
html += '
';
html += '
';
html += '
';
html += ' ';
html += '';
html += '
';
html += '
';
html += '
';
html += '
';
html += ' ';
html += '';
html += '
';
html += '
';
html += '
';
html += '
';
html += ' ';
html += '';
html += '
';
html += '
';
html += '
';
html += '
';
html += '
';
html += '';
html += '
';
html += '
';
html += '
';
return html;
}jQuery(function($) {
BranchesModuleInitialize();
});
/**
* The function initialize the Branches Module.
*/
function BranchesModuleInitialize() {
$( document ).on( 's123.page.ready', function( event ) {
var $section = $('section.s123-module-branches');
$section.each(function( index ) {
var $sectionThis = $(this);
if( $sectionThis.find(".coordinates").length > 0 ) {
var coordinates = JSON.parse($sectionThis.find(".coordinates").html());
} else {
coordinates = {};
}
var $branchtitle = $sectionThis.find('.title');
$.each($branchtitle, function( index, branchtitle) {
$(branchtitle).attr('href','https://maps.google.com/maps/place/' + coordinates[index].lat + ',' + coordinates[index].lng);
});
$sectionThis.find('.branch-phone-btn').click(function() {
var $this = $(this);
var $branchPhone = $this.closest('.branch-phone');
buildPopup('brancPopupFloatDivPhone','',$branchPhone.find('.branch-phone-popover').html(),'',true,true,true,'','');
});
$sectionThis.find('.branch-fax-btn').click(function() {
var $this = $(this);
var $branchFax = $this.closest('.branch-fax');
buildPopup('brancPopupFloatDivFax','',$branchFax.find('.branch-fax-popover').html(),'',true,true,true,'','');
});
$sectionThis.find('.google-map-obj').each( function( index ) {
var $this = $(this);
/**
* There is no option to get an exist instance of GMaps and
* every time its load it include some JS files. To prevent
* reinitialize of an exist object we set a custom flag.
*/
if ( !$this.data('gmapInit') ) {
var map = new GMaps({
div: '#'+$this.attr('id'),
lat: '',
lng: '',
scrollwheel: false,
draggable: isMobile.any() ? false : true
});
/**
* Set array that will contain the bounds info
* that Google maps need in order to display all of the markers.
*/
var bounds = [];
/*
*Create Loop that will add the markers by the coordinates from the JSON that is called "coordinates"
*and simultaneously convert the coordinates to Google "LatLng" object then push to the array bounds.
*/
for (var i = 0; i< coordinates.length; i++) {
map.addMarker({
lat: coordinates[i].lat,
lng: coordinates[i].lng
});
var latlng = new google.maps.LatLng(coordinates[i].lat, coordinates[i].lng);
bounds.push(latlng);
}
map.fitLatLngBounds(bounds);
$this.data('gmapInit',true);
}
});
$sectionThis.find('.send-mail').click(function() {
var $emailIcon = $(this);
var websiteID = $emailIcon.data('website-id');
var moduleID = $emailIcon.data('module-id');
var uniqueID = $emailIcon.data('unique-id');
var w = $('#w').val();
var branchInfo = {};
branchInfo.websiteID = websiteID;
branchInfo.moduleID = moduleID;
branchInfo.uniqueID = uniqueID;
branchInfo.w = w;
branchInfo.branchName = $emailIcon.data('branch-name');
branchInfo.branchEmail = getBranchemail(branchInfo.uniqueID , $emailIcon);
buildPopup('popupBranch','',buildBranchForm(branchInfo),'',true,false,true,'','');
$('#popupBranch').find('.branchForm').each( function( index ) {
var $form = $(this);
/**
* jQuery Validation Plugin Initial
* Documentation : http://jqueryvalidation.org/documentation/
*/
$form.validate({
errorElement: 'div',
errorClass: 'help-block',
focusInvalid: true,
ignore: "",
highlight: function (e) {
$(e).closest('.form-group').removeClass('has-info').addClass('has-error');
},
success: function (e) {
$(e).closest('.form-group').removeClass('has-error');
$(e).remove();
},
submitHandler: function( form ) {
var $form = $(form);
$form.find('button:submit').prop('disabled', true);
var $branchLoadingMessage = $('
'+translations.loading+'
');
var bootboxDialog = bootbox.alert({
title: translations.sending,
message: $branchLoadingMessage,
className: 'branchConfirm, bootbox-branch-form',
backdrop: true
}).on("hidden.bs.modal", function() {
buildPopup_CloseAction('popupBranch');
});
$.ajax({
type: "POST",
url: "/versions/"+$('#versionNUM').val()+"/include/branchO.php",
data: $form.serialize(),
success: function( data ) {
$form.trigger("reset");
message = ''+translations.ThankYou+'';
var $sentMessage = $(message);
bootboxDialog.find('.modal-title').html(translations.sent);
bootboxDialog.find('.bootbox-body').append($sentMessage.hide());
$branchLoadingMessage.hide();
$sentMessage.slideDown(200);
$form.find('button:submit').prop('disabled', false);
}
});
return false;
}
});
});
});
$.each($sectionThis.find('.branch'), function( index, branchContainer) {
buisnessHoursTemplate.init({
$buisnessHourContainer : $(branchContainer).find('.businessWorkingDays'),
buisnessHourJSON : $(branchContainer).find('.branchWorkingDays')
});
});
});
});
}
function getBranchemail( uniqueID , $emailIcon) {
var email = '';
$.each($emailIcon,function( index, emailIcon ) {
if($(emailIcon).data('unique-id') == uniqueID) {
email = $(emailIcon).find('input').val();
}
});
return email;
}
/**
* The function build the html of the branch form
* @param {string} websiteID - Website ID.
* @param {string} moduleID - Module ID.
* @param {string} uniqueID - Unique item ID.
* @return {string} html - Html of the form.
*/
function buildBranchForm( branchInfo ) {
var websiteID = branchInfo.websiteID;
var moduleID = branchInfo.moduleID;
var uniqueID = branchInfo.uniqueID;
var w = branchInfo.w;
var branchEmail = branchInfo.branchEmail;
var branchName = branchInfo.branchName;
var html = '';
html += '';
return html;
}var buisnessHoursTemplate = new function() {
var buisnessHTemplate = this;
buisnessHTemplate.init = function( settings ) {
var $buisnessHourContainer = settings.$buisnessHourContainer;
$buisnessHourContainer.empty();
var buisnessHourJSON = tryParseJSON(settings.buisnessHourJSON.val());
if(buisnessHourJSON.fullTime == 'on') {
buisnessHTemplate.twentyFourSevenTemplate($buisnessHourContainer);
return false;
}
var workingDaysContainer = {};
workingDaysContainer.$businessWorkingDays = settings.$buisnessHourContainer;
workingDaysContainer.weeklyWorkingTime = buisnessHourJSON;
buisnessHTemplate.showOpeningTime(workingDaysContainer);
};
this.firstDayOfTheWeek = function ( firstDayOfWeek ) {
var firstDayOfWeek = parseInt( firstDayOfWeek );
var daysOfWeek = [translations.Sunday, translations.Monday, translations.Tuesday, translations.Wednesday, translations.Thursday, translations.Friday, translations.Saturday ];
for( var i = 0 ; i < firstDayOfWeek ; i++ ) {
daysOfWeek.push(daysOfWeek[i]);
}
daysOfWeek.splice(0,firstDayOfWeek);
return daysOfWeek;
}
this.showOpeningTime = function ( workingDaysContainer ) {
var objtContainer = {};
objtContainer.daysOfWeek = buisnessHTemplate.firstDayOfTheWeek( workingDaysContainer.weeklyWorkingTime.firstDayOfWeek);
objtContainer.$label = workingDaysContainer.$businessWorkingDays;
objtContainer.templateNumber = workingDaysContainer.$businessWorkingDays.data('template');
objtContainer.dateFormat = workingDaysContainer.weeklyWorkingTime.dateFormat;
objtContainer.timeFormat = workingDaysContainer.weeklyWorkingTime.timeFormat;
objtContainer.weeklyDaysArray = workingDaysContainer.weeklyWorkingTime.businessHours;
switch(objtContainer.templateNumber) {
case 0:
objtContainer.days = buisnessHTemplate.sequenceTemplate(objtContainer);
buisnessHTemplate.generateHTML(objtContainer);
break;
case 1:
buisnessHTemplate.generateHTML(objtContainer);
break;
}
};
this.twentyFourSevenTemplate = function ( $label ) {
var html = '
24/7
';
$label.append(html);
}
/* sequence of days array
* [
* [{Sunday},{Monday}], <- sequence
[{Tuesday},{Wednesday}], <- sequence
[{Friday},{Saturday}] <- sequence
* ]
*/
this.sequenceTemplate = function ( objtContainer ) {
var daysOfWeek = objtContainer.daysOfWeek;
var weeklyDaysArray = objtContainer.weeklyDaysArray;
var templateNumber = objtContainer.templateNumber;
var $label = objtContainer.$label;
var days = new Array();
var datesSequence = new Array();
days.push(datesSequence);
$.each(weeklyDaysArray,function( index, weeklyDays ) {
if(weeklyDays.isActive) {
weeklyDays.index = index;
weeklyDays.name = daysOfWeek[index];
datesSequence.push(weeklyDays);
return false;
}
});
var arrayIndex = 0;
var skipStep = true;
var compareIndex = 0;
if(datesSequence.length <= 0) return false;
$.each(weeklyDaysArray,function( index, weeklyDays ) {
if( skipStep ) {
if(compareIndex < datesSequence[0].index) {
compareIndex ++ ;
return;
}
else {
skipStep = false;
}
}
weeklyDays.name = daysOfWeek[index];
weeklyDays.index = index;
if(weeklyDays.isActive) {
if(weeklyDays.name == datesSequence[arrayIndex].name) return;
/*
* compare the current date that the loop is on and the one from the sequence array,
* if the shifts are the same then push this day to the sequence
*/
if( weeklyDays.startTime1 == datesSequence[arrayIndex].startTime1
&& weeklyDays.endTime1 == datesSequence[arrayIndex].endTime1
&& weeklyDays.startTime2 == datesSequence[arrayIndex].startTime2
&& weeklyDays.endTime2 == datesSequence[arrayIndex].endTime2
&& weeklyDays.startTime3 == datesSequence[arrayIndex].startTime3
&& weeklyDays.endTime3 == datesSequence[arrayIndex].endTime3 ) {
if(index - datesSequence[arrayIndex].index == 1) {
datesSequence.push(weeklyDays);
arrayIndex ++ ;
} else {
datesSequence = new Array();
datesSequence.push(weeklyDays);
days.push(datesSequence);
arrayIndex = 0;
}
} else {
datesSequence = new Array();
datesSequence.push(weeklyDays);
days.push(datesSequence);
arrayIndex = 0;
}
}
});
return days;
};
this.changeTimeFormat = function( websiteTimeFormat, time ) {
switch( websiteTimeFormat ) {
case 'H:i':
return moment(time,"hmm").format("HH:mm");
break;
case 'h:i A':
return moment(time,"hmm").format("hh:mm A");
break;
}
};
this.generateHTML = function ( objtContainer ) {
var days = objtContainer.days;
var daysOfWeek = objtContainer.daysOfWeek;
var weeklyDaysArray = objtContainer.weeklyDaysArray;
var templateNumber = objtContainer.templateNumber;
var $label = objtContainer.$label;
var websiteTimeFormat = objtContainer.timeFormat;
var html = '';
switch( templateNumber ) {
case 0:
/*
* This loop is crating html output of the sequence array example:
* [
* [{Sunday},{Monday}], <- sequence
[{Tuesday},{Wednesday}], <- sequence
[{Friday},{Saturday}] <- sequence
* ]
*/
$.each(days, function( index, workingDays ) {
if (workingDays.length == 1) {
workingDays[0].startTime1 = buisnessHTemplate.changeTimeFormat(websiteTimeFormat,workingDays[0].startTime1);
workingDays[0].endTime1 = buisnessHTemplate.changeTimeFormat(websiteTimeFormat,workingDays[0].endTime1);
html += '
');
}
}
clsName = this.getClassNames(prevMonth);
clsName.push('day');
var content = prevMonth.getUTCDate();
if (this.o.beforeShowDay !== $.noop){
before = this.o.beforeShowDay(this._utc_to_local(prevMonth));
if (before === undefined)
before = {};
else if (typeof before === 'boolean')
before = {enabled: before};
else if (typeof before === 'string')
before = {classes: before};
if (before.enabled === false)
clsName.push('disabled');
if (before.classes)
clsName = clsName.concat(before.classes.split(/\s+/));
if (before.tooltip)
tooltip = before.tooltip;
if (before.content)
content = before.content;
}
if ($.isFunction($.uniqueSort)) {
clsName = $.uniqueSort(clsName);
} else {
clsName = $.unique(clsName);
}
html.push('
' + content + '
');
tooltip = null;
if (weekDay === this.o.weekEnd){
html.push('
');
}
prevMonth.setUTCDate(prevMonth.getUTCDate() + 1);
}
this.picker.find('.datepicker-days tbody').html(html.join(''));
var monthsTitle = dates[this.o.language].monthsTitle || dates['en'].monthsTitle || 'Months';
var months = this.picker.find('.datepicker-months')
.find('.datepicker-switch')
.text(this.o.maxViewMode < 2 ? monthsTitle : year)
.end()
.find('tbody span').removeClass('active');
$.each(this.dates, function(i, d){
if (d.getUTCFullYear() === year)
months.eq(d.getUTCMonth()).addClass('active');
});
if (year < startYear || year > endYear){
months.addClass('disabled');
}
if (year === startYear){
months.slice(0, startMonth).addClass('disabled');
}
if (year === endYear){
months.slice(endMonth+1).addClass('disabled');
}
if (this.o.beforeShowMonth !== $.noop){
var that = this;
$.each(months, function(i, month){
var moDate = new Date(year, i, 1);
var before = that.o.beforeShowMonth(moDate);
if (before === undefined)
before = {};
else if (typeof before === 'boolean')
before = {enabled: before};
else if (typeof before === 'string')
before = {classes: before};
if (before.enabled === false && !$(month).hasClass('disabled'))
$(month).addClass('disabled');
if (before.classes)
$(month).addClass(before.classes);
if (before.tooltip)
$(month).prop('title', before.tooltip);
});
}
this._fill_yearsView(
'.datepicker-years',
'year',
10,
year,
startYear,
endYear,
this.o.beforeShowYear
);
this._fill_yearsView(
'.datepicker-decades',
'decade',
100,
year,
startYear,
endYear,
this.o.beforeShowDecade
);
this._fill_yearsView(
'.datepicker-centuries',
'century',
1000,
year,
startYear,
endYear,
this.o.beforeShowCentury
);
},
updateNavArrows: function(){
if (!this._allow_update)
return;
var d = new Date(this.viewDate),
year = d.getUTCFullYear(),
month = d.getUTCMonth(),
startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity,
startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity,
endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity,
endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity,
prevIsDisabled,
nextIsDisabled,
factor = 1;
switch (this.viewMode){
case 0:
prevIsDisabled = year <= startYear && month <= startMonth;
nextIsDisabled = year >= endYear && month >= endMonth;
break;
case 4:
factor *= 10;
/* falls through */
case 3:
factor *= 10;
/* falls through */
case 2:
factor *= 10;
/* falls through */
case 1:
prevIsDisabled = Math.floor(year / factor) * factor <= startYear;
nextIsDisabled = Math.floor(year / factor) * factor + factor >= endYear;
break;
}
this.picker.find('.prev').toggleClass('disabled', prevIsDisabled);
this.picker.find('.next').toggleClass('disabled', nextIsDisabled);
},
click: function(e){
e.preventDefault();
e.stopPropagation();
var target, dir, day, year, month;
target = $(e.target);
if (target.hasClass('datepicker-switch') && this.viewMode !== this.o.maxViewMode){
this.setViewMode(this.viewMode + 1);
}
if (target.hasClass('today') && !target.hasClass('day')){
this.setViewMode(0);
this._setDate(UTCToday(), this.o.todayBtn === 'linked' ? null : 'view');
}
if (target.hasClass('clear')){
this.clearDates();
}
if (!target.hasClass('disabled')){
if (target.hasClass('month')
|| target.hasClass('year')
|| target.hasClass('decade')
|| target.hasClass('century')) {
this.viewDate.setUTCDate(1);
day = 1;
if (this.viewMode === 1){
month = target.parent().find('span').index(target);
year = this.viewDate.getUTCFullYear();
this.viewDate.setUTCMonth(month);
} else {
month = 0;
year = Number(target.text());
this.viewDate.setUTCFullYear(year);
}
this._trigger(DPGlobal.viewModes[this.viewMode - 1].e, this.viewDate);
if (this.viewMode === this.o.minViewMode){
this._setDate(UTCDate(year, month, day));
} else {
this.setViewMode(this.viewMode - 1);
this.fill();
}
}
}
if (this.picker.is(':visible') && this._focused_from){
this._focused_from.focus();
}
delete this._focused_from;
},
dayCellClick: function(e){
var $target = $(e.currentTarget);
var timestamp = $target.data('date');
var date = new Date(timestamp);
if (this.o.updateViewDate) {
if (date.getUTCFullYear() !== this.viewDate.getUTCFullYear()) {
this._trigger('changeYear', this.viewDate);
}
if (date.getUTCMonth() !== this.viewDate.getUTCMonth()) {
this._trigger('changeMonth', this.viewDate);
}
}
this._setDate(date);
},
navArrowsClick: function(e){
var $target = $(e.currentTarget);
var dir = $target.hasClass('prev') ? -1 : 1;
if (this.viewMode !== 0){
dir *= DPGlobal.viewModes[this.viewMode].navStep * 12;
}
this.viewDate = this.moveMonth(this.viewDate, dir);
this._trigger(DPGlobal.viewModes[this.viewMode].e, this.viewDate);
this.fill();
},
_toggle_multidate: function(date){
var ix = this.dates.contains(date);
if (!date){
this.dates.clear();
}
if (ix !== -1){
if (this.o.multidate === true || this.o.multidate > 1 || this.o.toggleActive){
this.dates.remove(ix);
}
} else if (this.o.multidate === false) {
this.dates.clear();
this.dates.push(date);
}
else {
this.dates.push(date);
}
if (typeof this.o.multidate === 'number')
while (this.dates.length > this.o.multidate)
this.dates.remove(0);
},
_setDate: function(date, which){
if (!which || which === 'date')
this._toggle_multidate(date && new Date(date));
if ((!which && this.o.updateViewDate) || which === 'view')
this.viewDate = date && new Date(date);
this.fill();
this.setValue();
if (!which || which !== 'view') {
this._trigger('changeDate');
}
this.inputField.trigger('change');
if (this.o.autoclose && (!which || which === 'date')){
this.hide();
}
},
moveDay: function(date, dir){
var newDate = new Date(date);
newDate.setUTCDate(date.getUTCDate() + dir);
return newDate;
},
moveWeek: function(date, dir){
return this.moveDay(date, dir * 7);
},
moveMonth: function(date, dir){
if (!isValidDate(date))
return this.o.defaultViewDate;
if (!dir)
return date;
var new_date = new Date(date.valueOf()),
day = new_date.getUTCDate(),
month = new_date.getUTCMonth(),
mag = Math.abs(dir),
new_month, test;
dir = dir > 0 ? 1 : -1;
if (mag === 1){
test = dir === -1
? function(){
return new_date.getUTCMonth() === month;
}
: function(){
return new_date.getUTCMonth() !== new_month;
};
new_month = month + dir;
new_date.setUTCMonth(new_month);
new_month = (new_month + 12) % 12;
}
else {
for (var i=0; i < mag; i++)
new_date = this.moveMonth(new_date, dir);
new_month = new_date.getUTCMonth();
new_date.setUTCDate(day);
test = function(){
return new_month !== new_date.getUTCMonth();
};
}
while (test()){
new_date.setUTCDate(--day);
new_date.setUTCMonth(new_month);
}
return new_date;
},
moveYear: function(date, dir){
return this.moveMonth(date, dir*12);
},
moveAvailableDate: function(date, dir, fn){
do {
date = this[fn](date, dir);
if (!this.dateWithinRange(date))
return false;
fn = 'moveDay';
}
while (this.dateIsDisabled(date));
return date;
},
weekOfDateIsDisabled: function(date){
return $.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1;
},
dateIsDisabled: function(date){
return (
this.weekOfDateIsDisabled(date) ||
$.grep(this.o.datesDisabled, function(d){
return isUTCEquals(date, d);
}).length > 0
);
},
dateWithinRange: function(date){
return date >= this.o.startDate && date <= this.o.endDate;
},
keydown: function(e){
if (!this.picker.is(':visible')){
if (e.keyCode === 40 || e.keyCode === 27) { // allow down to re-show picker
this.show();
e.stopPropagation();
}
return;
}
var dateChanged = false,
dir, newViewDate,
focusDate = this.focusDate || this.viewDate;
switch (e.keyCode){
case 27: // escape
if (this.focusDate){
this.focusDate = null;
this.viewDate = this.dates.get(-1) || this.viewDate;
this.fill();
}
else
this.hide();
e.preventDefault();
e.stopPropagation();
break;
case 37: // left
case 38: // up
case 39: // right
case 40: // down
if (!this.o.keyboardNavigation || this.o.daysOfWeekDisabled.length === 7)
break;
dir = e.keyCode === 37 || e.keyCode === 38 ? -1 : 1;
if (this.viewMode === 0) {
if (e.ctrlKey){
newViewDate = this.moveAvailableDate(focusDate, dir, 'moveYear');
if (newViewDate)
this._trigger('changeYear', this.viewDate);
} else if (e.shiftKey){
newViewDate = this.moveAvailableDate(focusDate, dir, 'moveMonth');
if (newViewDate)
this._trigger('changeMonth', this.viewDate);
} else if (e.keyCode === 37 || e.keyCode === 39){
newViewDate = this.moveAvailableDate(focusDate, dir, 'moveDay');
} else if (!this.weekOfDateIsDisabled(focusDate)){
newViewDate = this.moveAvailableDate(focusDate, dir, 'moveWeek');
}
} else if (this.viewMode === 1) {
if (e.keyCode === 38 || e.keyCode === 40) {
dir = dir * 4;
}
newViewDate = this.moveAvailableDate(focusDate, dir, 'moveMonth');
} else if (this.viewMode === 2) {
if (e.keyCode === 38 || e.keyCode === 40) {
dir = dir * 4;
}
newViewDate = this.moveAvailableDate(focusDate, dir, 'moveYear');
}
if (newViewDate){
this.focusDate = this.viewDate = newViewDate;
this.setValue();
this.fill();
e.preventDefault();
}
break;
case 13: // enter
if (!this.o.forceParse)
break;
focusDate = this.focusDate || this.dates.get(-1) || this.viewDate;
if (this.o.keyboardNavigation) {
this._toggle_multidate(focusDate);
dateChanged = true;
}
this.focusDate = null;
this.viewDate = this.dates.get(-1) || this.viewDate;
this.setValue();
this.fill();
if (this.picker.is(':visible')){
e.preventDefault();
e.stopPropagation();
if (this.o.autoclose)
this.hide();
}
break;
case 9: // tab
this.focusDate = null;
this.viewDate = this.dates.get(-1) || this.viewDate;
this.fill();
this.hide();
break;
}
if (dateChanged){
if (this.dates.length)
this._trigger('changeDate');
else
this._trigger('clearDate');
this.inputField.trigger('change');
}
},
setViewMode: function(viewMode){
this.viewMode = viewMode;
this.picker
.children('div')
.hide()
.filter('.datepicker-' + DPGlobal.viewModes[this.viewMode].clsName)
.show();
this.updateNavArrows();
this._trigger('changeViewMode', new Date(this.viewDate));
}
};
var DateRangePicker = function(element, options){
$.data(element, 'datepicker', this);
this.element = $(element);
this.inputs = $.map(options.inputs, function(i){
return i.jquery ? i[0] : i;
});
delete options.inputs;
this.keepEmptyValues = options.keepEmptyValues;
delete options.keepEmptyValues;
datepickerPlugin.call($(this.inputs), options)
.on('changeDate', $.proxy(this.dateUpdated, this));
this.pickers = $.map(this.inputs, function(i){
return $.data(i, 'datepicker');
});
this.updateDates();
};
DateRangePicker.prototype = {
updateDates: function(){
this.dates = $.map(this.pickers, function(i){
return i.getUTCDate();
});
this.updateRanges();
},
updateRanges: function(){
var range = $.map(this.dates, function(d){
return d.valueOf();
});
$.each(this.pickers, function(i, p){
p.setRange(range);
});
},
dateUpdated: function(e){
if (this.updating)
return;
this.updating = true;
var dp = $.data(e.target, 'datepicker');
if (dp === undefined) {
return;
}
var new_date = dp.getUTCDate(),
keep_empty_values = this.keepEmptyValues,
i = $.inArray(e.target, this.inputs),
j = i - 1,
k = i + 1,
l = this.inputs.length;
if (i === -1)
return;
$.each(this.pickers, function(i, p){
if (!p.getUTCDate() && (p === dp || !keep_empty_values))
p.setUTCDate(new_date);
});
if (new_date < this.dates[j]){
while (j >= 0 && new_date < this.dates[j]){
this.pickers[j--].setUTCDate(new_date);
}
} else if (new_date > this.dates[k]){
while (k < l && new_date > this.dates[k]){
this.pickers[k++].setUTCDate(new_date);
}
}
this.updateDates();
delete this.updating;
},
destroy: function(){
$.map(this.pickers, function(p){ p.destroy(); });
$(this.inputs).off('changeDate', this.dateUpdated);
delete this.element.data().datepicker;
},
remove: alias('destroy', 'Method `remove` is deprecated and will be removed in version 2.0. Use `destroy` instead')
};
function opts_from_el(el, prefix){
var data = $(el).data(),
out = {}, inkey,
replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])');
prefix = new RegExp('^' + prefix.toLowerCase());
function re_lower(_,a){
return a.toLowerCase();
}
for (var key in data)
if (prefix.test(key)){
inkey = key.replace(replace, re_lower);
out[inkey] = data[key];
}
return out;
}
function opts_from_locale(lang){
var out = {};
if (!dates[lang]){
lang = lang.split('-')[0];
if (!dates[lang])
return;
}
var d = dates[lang];
$.each(locale_opts, function(i,k){
if (k in d)
out[k] = d[k];
});
return out;
}
var old = $.fn.datepicker;
var datepickerPlugin = function(option){
var args = Array.apply(null, arguments);
args.shift();
var internal_return;
this.each(function(){
var $this = $(this),
data = $this.data('datepicker'),
options = typeof option === 'object' && option;
if (!data){
var elopts = opts_from_el(this, 'date'),
xopts = $.extend({}, defaults, elopts, options),
locopts = opts_from_locale(xopts.language),
opts = $.extend({}, defaults, locopts, elopts, options);
if ($this.hasClass('input-daterange') || opts.inputs){
$.extend(opts, {
inputs: opts.inputs || $this.find('input').toArray()
});
data = new DateRangePicker(this, opts);
}
else {
data = new Datepicker(this, opts);
}
$this.data('datepicker', data);
}
if (typeof option === 'string' && typeof data[option] === 'function'){
internal_return = data[option].apply(data, args);
}
});
if (
internal_return === undefined ||
internal_return instanceof Datepicker ||
internal_return instanceof DateRangePicker
)
return this;
if (this.length > 1)
throw new Error('Using only allowed for the collection of a single element (' + option + ' function)');
else
return internal_return;
};
$.fn.datepicker = datepickerPlugin;
var defaults = $.fn.datepicker.defaults = {
assumeNearbyYear: false,
autoclose: false,
beforeShowDay: $.noop,
beforeShowMonth: $.noop,
beforeShowYear: $.noop,
beforeShowDecade: $.noop,
beforeShowCentury: $.noop,
calendarWeeks: false,
clearBtn: false,
toggleActive: false,
daysOfWeekDisabled: [],
daysOfWeekHighlighted: [],
datesDisabled: [],
endDate: Infinity,
forceParse: true,
format: 'mm/dd/yyyy',
keepEmptyValues: false,
keyboardNavigation: true,
language: 'en',
minViewMode: 0,
maxViewMode: 4,
multidate: false,
multidateSeparator: ',',
orientation: "auto",
rtl: false,
startDate: -Infinity,
startView: 0,
todayBtn: false,
todayHighlight: false,
updateViewDate: true,
weekStart: 0,
disableTouchKeyboard: false,
enableOnReadonly: true,
showOnFocus: true,
zIndexOffset: 10,
container: 'body',
immediateUpdates: false,
title: '',
templates: {
leftArrow: '«',
rightArrow: '»'
},
showWeekDays: true
};
var locale_opts = $.fn.datepicker.locale_opts = [
'format',
'rtl',
'weekStart'
];
$.fn.datepicker.Constructor = Datepicker;
var dates = $.fn.datepicker.dates = {
en: {
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
today: "Today",
clear: "Clear",
titleFormat: "MM yyyy"
}
};
var DPGlobal = {
viewModes: [
{
names: ['days', 'month'],
clsName: 'days',
e: 'changeMonth'
},
{
names: ['months', 'year'],
clsName: 'months',
e: 'changeYear',
navStep: 1
},
{
names: ['years', 'decade'],
clsName: 'years',
e: 'changeDecade',
navStep: 10
},
{
names: ['decades', 'century'],
clsName: 'decades',
e: 'changeCentury',
navStep: 100
},
{
names: ['centuries', 'millennium'],
clsName: 'centuries',
e: 'changeMillennium',
navStep: 1000
}
],
validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
nonpunctuation: /[^ -\/:-@\u5e74\u6708\u65e5\[-`{-~\t\n\r]+/g,
parseFormat: function(format){
if (typeof format.toValue === 'function' && typeof format.toDisplay === 'function')
return format;
var separators = format.replace(this.validParts, '\0').split('\0'),
parts = format.match(this.validParts);
if (!separators || !separators.length || !parts || parts.length === 0){
throw new Error("Invalid date format.");
}
return {separators: separators, parts: parts};
},
parseDate: function(date, format, language, assumeNearby){
if (!date)
return undefined;
if (date instanceof Date)
return date;
if (typeof format === 'string')
format = DPGlobal.parseFormat(format);
if (format.toValue)
return format.toValue(date, format, language);
var fn_map = {
d: 'moveDay',
m: 'moveMonth',
w: 'moveWeek',
y: 'moveYear'
},
dateAliases = {
yesterday: '-1d',
today: '+0d',
tomorrow: '+1d'
},
parts, part, dir, i, fn;
if (date in dateAliases){
date = dateAliases[date];
}
if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/i.test(date)){
parts = date.match(/([\-+]\d+)([dmwy])/gi);
date = new Date();
for (i=0; i < parts.length; i++){
part = parts[i].match(/([\-+]\d+)([dmwy])/i);
dir = Number(part[1]);
fn = fn_map[part[2].toLowerCase()];
date = Datepicker.prototype[fn](date, dir);
}
return Datepicker.prototype._zero_utc_time(date);
}
parts = date && date.match(this.nonpunctuation) || [];
function applyNearbyYear(year, threshold){
if (threshold === true)
threshold = 10;
if (year < 100){
year += 2000;
if (year > ((new Date()).getFullYear()+threshold)){
year -= 100;
}
}
return year;
}
var parsed = {},
setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'],
setters_map = {
yyyy: function(d,v){
return d.setUTCFullYear(assumeNearby ? applyNearbyYear(v, assumeNearby) : v);
},
m: function(d,v){
if (isNaN(d))
return d;
v -= 1;
while (v < 0) v += 12;
v %= 12;
d.setUTCMonth(v);
while (d.getUTCMonth() !== v)
d.setUTCDate(d.getUTCDate()-1);
return d;
},
d: function(d,v){
return d.setUTCDate(v);
}
},
val, filtered;
setters_map['yy'] = setters_map['yyyy'];
setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
setters_map['dd'] = setters_map['d'];
date = UTCToday();
var fparts = format.parts.slice();
if (parts.length !== fparts.length){
fparts = $(fparts).filter(function(i,p){
return $.inArray(p, setters_order) !== -1;
}).toArray();
}
function match_part(){
var m = this.slice(0, parts[i].length),
p = parts[i].slice(0, m.length);
return m.toLowerCase() === p.toLowerCase();
}
if (parts.length === fparts.length){
var cnt;
for (i=0, cnt = fparts.length; i < cnt; i++){
val = parseInt(parts[i], 10);
part = fparts[i];
if (isNaN(val)){
switch (part){
case 'MM':
filtered = $(dates[language].months).filter(match_part);
val = $.inArray(filtered[0], dates[language].months) + 1;
break;
case 'M':
filtered = $(dates[language].monthsShort).filter(match_part);
val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
break;
}
}
parsed[part] = val;
}
var _date, s;
for (i=0; i < setters_order.length; i++){
s = setters_order[i];
if (s in parsed && !isNaN(parsed[s])){
_date = new Date(date);
setters_map[s](_date, parsed[s]);
if (!isNaN(_date))
date = _date;
}
}
}
return date;
},
formatDate: function(date, format, language){
if (!date)
return '';
if (typeof format === 'string')
format = DPGlobal.parseFormat(format);
if (format.toDisplay)
return format.toDisplay(date, format, language);
var val = {
d: date.getUTCDate(),
D: dates[language].daysShort[date.getUTCDay()],
DD: dates[language].days[date.getUTCDay()],
m: date.getUTCMonth() + 1,
M: dates[language].monthsShort[date.getUTCMonth()],
MM: dates[language].months[date.getUTCMonth()],
yy: date.getUTCFullYear().toString().substring(2),
yyyy: date.getUTCFullYear()
};
val.dd = (val.d < 10 ? '0' : '') + val.d;
val.mm = (val.m < 10 ? '0' : '') + val.m;
date = [];
var seps = $.extend([], format.separators);
for (var i=0, cnt = format.parts.length; i <= cnt; i++){
if (seps.length)
date.push(seps.shift());
date.push(val[format.parts[i]]);
}
return date.join('');
},
headTemplate: ''+
'
';
$.fn.datepicker.DPGlobal = DPGlobal;
/* DATEPICKER NO CONFLICT
* =================== */
$.fn.datepicker.noConflict = function(){
$.fn.datepicker = old;
return this;
};
/* DATEPICKER VERSION
* =================== */
$.fn.datepicker.version = '1.7.1';
$.fn.datepicker.deprecated = function(msg){
var console = window.console;
if (console && console.warn) {
console.warn('DEPRECATED: ' + msg);
}
};
/* DATEPICKER DATA-API
* ================== */
$(document).on(
'focus.datepicker.data-api click.datepicker.data-api',
'[data-provide="datepicker"]',
function(e){
var $this = $(this);
if ($this.data('datepicker'))
return;
e.preventDefault();
datepickerPlugin.call($this, 'show');
}
);
$(function(){
datepickerPlugin.call($('[data-provide="datepicker-inline"]'));
});
}));//! moment.js
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
global.moment = factory()
}(this, function () { 'use strict';
var hookCallback;
function utils_hooks__hooks () {
return hookCallback.apply(null, arguments);
}
function setHookCallback (callback) {
hookCallback = callback;
}
function isArray(input) {
return Object.prototype.toString.call(input) === '[object Array]';
}
function isDate(input) {
return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
}
function map(arr, fn) {
var res = [], i;
for (i = 0; i < arr.length; ++i) {
res.push(fn(arr[i], i));
}
return res;
}
function hasOwnProp(a, b) {
return Object.prototype.hasOwnProperty.call(a, b);
}
function extend(a, b) {
for (var i in b) {
if (hasOwnProp(b, i)) {
a[i] = b[i];
}
}
if (hasOwnProp(b, 'toString')) {
a.toString = b.toString;
}
if (hasOwnProp(b, 'valueOf')) {
a.valueOf = b.valueOf;
}
return a;
}
function create_utc__createUTC (input, format, locale, strict) {
return createLocalOrUTC(input, format, locale, strict, true).utc();
}
function defaultParsingFlags() {
return {
empty : false,
unusedTokens : [],
unusedInput : [],
overflow : -2,
charsLeftOver : 0,
nullInput : false,
invalidMonth : null,
invalidFormat : false,
userInvalidated : false,
iso : false
};
}
function getParsingFlags(m) {
if (m._pf == null) {
m._pf = defaultParsingFlags();
}
return m._pf;
}
function valid__isValid(m) {
if (m._isValid == null) {
var flags = getParsingFlags(m);
m._isValid = !isNaN(m._d.getTime()) &&
flags.overflow < 0 &&
!flags.empty &&
!flags.invalidMonth &&
!flags.invalidWeekday &&
!flags.nullInput &&
!flags.invalidFormat &&
!flags.userInvalidated;
if (m._strict) {
m._isValid = m._isValid &&
flags.charsLeftOver === 0 &&
flags.unusedTokens.length === 0 &&
flags.bigHour === undefined;
}
}
return m._isValid;
}
function valid__createInvalid (flags) {
var m = create_utc__createUTC(NaN);
if (flags != null) {
extend(getParsingFlags(m), flags);
}
else {
getParsingFlags(m).userInvalidated = true;
}
return m;
}
var momentProperties = utils_hooks__hooks.momentProperties = [];
function copyConfig(to, from) {
var i, prop, val;
if (typeof from._isAMomentObject !== 'undefined') {
to._isAMomentObject = from._isAMomentObject;
}
if (typeof from._i !== 'undefined') {
to._i = from._i;
}
if (typeof from._f !== 'undefined') {
to._f = from._f;
}
if (typeof from._l !== 'undefined') {
to._l = from._l;
}
if (typeof from._strict !== 'undefined') {
to._strict = from._strict;
}
if (typeof from._tzm !== 'undefined') {
to._tzm = from._tzm;
}
if (typeof from._isUTC !== 'undefined') {
to._isUTC = from._isUTC;
}
if (typeof from._offset !== 'undefined') {
to._offset = from._offset;
}
if (typeof from._pf !== 'undefined') {
to._pf = getParsingFlags(from);
}
if (typeof from._locale !== 'undefined') {
to._locale = from._locale;
}
if (momentProperties.length > 0) {
for (i in momentProperties) {
prop = momentProperties[i];
val = from[prop];
if (typeof val !== 'undefined') {
to[prop] = val;
}
}
}
return to;
}
var updateInProgress = false;
function Moment(config) {
copyConfig(this, config);
this._d = new Date(config._d != null ? config._d.getTime() : NaN);
if (updateInProgress === false) {
updateInProgress = true;
utils_hooks__hooks.updateOffset(this);
updateInProgress = false;
}
}
function isMoment (obj) {
return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
}
function absFloor (number) {
if (number < 0) {
return Math.ceil(number);
} else {
return Math.floor(number);
}
}
function toInt(argumentForCoercion) {
var coercedNumber = +argumentForCoercion,
value = 0;
if (coercedNumber !== 0 && isFinite(coercedNumber)) {
value = absFloor(coercedNumber);
}
return value;
}
function compareArrays(array1, array2, dontConvert) {
var len = Math.min(array1.length, array2.length),
lengthDiff = Math.abs(array1.length - array2.length),
diffs = 0,
i;
for (i = 0; i < len; i++) {
if ((dontConvert && array1[i] !== array2[i]) ||
(!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
diffs++;
}
}
return diffs + lengthDiff;
}
function Locale() {
}
var locales = {};
var globalLocale;
function normalizeLocale(key) {
return key ? key.toLowerCase().replace('_', '-') : key;
}
function chooseLocale(names) {
var i = 0, j, next, locale, split;
while (i < names.length) {
split = normalizeLocale(names[i]).split('-');
j = split.length;
next = normalizeLocale(names[i + 1]);
next = next ? next.split('-') : null;
while (j > 0) {
locale = loadLocale(split.slice(0, j).join('-'));
if (locale) {
return locale;
}
if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
break;
}
j--;
}
i++;
}
return null;
}
function loadLocale(name) {
var oldLocale = null;
if (!locales[name] && typeof module !== 'undefined' &&
module && module.exports) {
try {
oldLocale = globalLocale._abbr;
require('./locale/' + name);
locale_locales__getSetGlobalLocale(oldLocale);
} catch (e) { }
}
return locales[name];
}
function locale_locales__getSetGlobalLocale (key, values) {
var data;
if (key) {
if (typeof values === 'undefined') {
data = locale_locales__getLocale(key);
}
else {
data = defineLocale(key, values);
}
if (data) {
globalLocale = data;
}
}
return globalLocale._abbr;
}
function defineLocale (name, values) {
if (values !== null) {
values.abbr = name;
locales[name] = locales[name] || new Locale();
locales[name].set(values);
locale_locales__getSetGlobalLocale(name);
return locales[name];
} else {
delete locales[name];
return null;
}
}
function locale_locales__getLocale (key) {
var locale;
if (key && key._locale && key._locale._abbr) {
key = key._locale._abbr;
}
if (!key) {
return globalLocale;
}
if (!isArray(key)) {
locale = loadLocale(key);
if (locale) {
return locale;
}
key = [key];
}
return chooseLocale(key);
}
var aliases = {};
function addUnitAlias (unit, shorthand) {
var lowerCase = unit.toLowerCase();
aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
}
function normalizeUnits(units) {
return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
}
function normalizeObjectUnits(inputObject) {
var normalizedInput = {},
normalizedProp,
prop;
for (prop in inputObject) {
if (hasOwnProp(inputObject, prop)) {
normalizedProp = normalizeUnits(prop);
if (normalizedProp) {
normalizedInput[normalizedProp] = inputObject[prop];
}
}
}
return normalizedInput;
}
function makeGetSet (unit, keepTime) {
return function (value) {
if (value != null) {
get_set__set(this, unit, value);
utils_hooks__hooks.updateOffset(this, keepTime);
return this;
} else {
return get_set__get(this, unit);
}
};
}
function get_set__get (mom, unit) {
return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]();
}
function get_set__set (mom, unit, value) {
return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
}
function getSet (units, value) {
var unit;
if (typeof units === 'object') {
for (unit in units) {
this.set(unit, units[unit]);
}
} else {
units = normalizeUnits(units);
if (typeof this[units] === 'function') {
return this[units](value);
}
}
return this;
}
function zeroFill(number, targetLength, forceSign) {
var absNumber = '' + Math.abs(number),
zerosToFill = targetLength - absNumber.length,
sign = number >= 0;
return (sign ? (forceSign ? '+' : '') : '-') +
Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
}
var formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;
var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
var formatFunctions = {};
var formatTokenFunctions = {};
function addFormatToken (token, padded, ordinal, callback) {
var func = callback;
if (typeof callback === 'string') {
func = function () {
return this[callback]();
};
}
if (token) {
formatTokenFunctions[token] = func;
}
if (padded) {
formatTokenFunctions[padded[0]] = function () {
return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
};
}
if (ordinal) {
formatTokenFunctions[ordinal] = function () {
return this.localeData().ordinal(func.apply(this, arguments), token);
};
}
}
function removeFormattingTokens(input) {
if (input.match(/\[[\s\S]/)) {
return input.replace(/^\[|\]$/g, '');
}
return input.replace(/\\/g, '');
}
function makeFormatFunction(format) {
var array = format.match(formattingTokens), i, length;
for (i = 0, length = array.length; i < length; i++) {
if (formatTokenFunctions[array[i]]) {
array[i] = formatTokenFunctions[array[i]];
} else {
array[i] = removeFormattingTokens(array[i]);
}
}
return function (mom) {
var output = '';
for (i = 0; i < length; i++) {
output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
}
return output;
};
}
function formatMoment(m, format) {
if (!m.isValid()) {
return m.localeData().invalidDate();
}
format = expandFormat(format, m.localeData());
formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
return formatFunctions[format](m);
}
function expandFormat(format, locale) {
var i = 5;
function replaceLongDateFormatTokens(input) {
return locale.longDateFormat(input) || input;
}
localFormattingTokens.lastIndex = 0;
while (i >= 0 && localFormattingTokens.test(format)) {
format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
localFormattingTokens.lastIndex = 0;
i -= 1;
}
return format;
}
var match1 = /\d/; // 0 - 9
var match2 = /\d\d/; // 00 - 99
var match3 = /\d{3}/; // 000 - 999
var match4 = /\d{4}/; // 0000 - 9999
var match6 = /[+-]?\d{6}/; // -999999 - 999999
var match1to2 = /\d\d?/; // 0 - 99
var match1to3 = /\d{1,3}/; // 0 - 999
var match1to4 = /\d{1,4}/; // 0 - 9999
var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999
var matchUnsigned = /\d+/; // 0 - inf
var matchSigned = /[+-]?\d+/; // -inf - inf
var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i;
var regexes = {};
function isFunction (sth) {
return typeof sth === 'function' &&
Object.prototype.toString.call(sth) === '[object Function]';
}
function addRegexToken (token, regex, strictRegex) {
regexes[token] = isFunction(regex) ? regex : function (isStrict) {
return (isStrict && strictRegex) ? strictRegex : regex;
};
}
function getParseRegexForToken (token, config) {
if (!hasOwnProp(regexes, token)) {
return new RegExp(unescapeFormat(token));
}
return regexes[token](config._strict, config._locale);
}
function unescapeFormat(s) {
return s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
return p1 || p2 || p3 || p4;
}).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var tokens = {};
function addParseToken (token, callback) {
var i, func = callback;
if (typeof token === 'string') {
token = [token];
}
if (typeof callback === 'number') {
func = function (input, array) {
array[callback] = toInt(input);
};
}
for (i = 0; i < token.length; i++) {
tokens[token[i]] = func;
}
}
function addWeekParseToken (token, callback) {
addParseToken(token, function (input, array, config, token) {
config._w = config._w || {};
callback(input, config._w, config, token);
});
}
function addTimeToArrayFromToken(token, input, config) {
if (input != null && hasOwnProp(tokens, token)) {
tokens[token](input, config._a, config, token);
}
}
var YEAR = 0;
var MONTH = 1;
var DATE = 2;
var HOUR = 3;
var MINUTE = 4;
var SECOND = 5;
var MILLISECOND = 6;
function daysInMonth(year, month) {
return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
}
addFormatToken('M', ['MM', 2], 'Mo', function () {
return this.month() + 1;
});
addFormatToken('MMM', 0, 0, function (format) {
return this.localeData().monthsShort(this, format);
});
addFormatToken('MMMM', 0, 0, function (format) {
return this.localeData().months(this, format);
});
addUnitAlias('month', 'M');
addRegexToken('M', match1to2);
addRegexToken('MM', match1to2, match2);
addRegexToken('MMM', matchWord);
addRegexToken('MMMM', matchWord);
addParseToken(['M', 'MM'], function (input, array) {
array[MONTH] = toInt(input) - 1;
});
addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
var month = config._locale.monthsParse(input, token, config._strict);
if (month != null) {
array[MONTH] = month;
} else {
getParsingFlags(config).invalidMonth = input;
}
});
var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
function localeMonths (m) {
return this._months[m.month()];
}
var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
function localeMonthsShort (m) {
return this._monthsShort[m.month()];
}
function localeMonthsParse (monthName, format, strict) {
var i, mom, regex;
if (!this._monthsParse) {
this._monthsParse = [];
this._longMonthsParse = [];
this._shortMonthsParse = [];
}
for (i = 0; i < 12; i++) {
mom = create_utc__createUTC([2000, i]);
if (strict && !this._longMonthsParse[i]) {
this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
}
if (!strict && !this._monthsParse[i]) {
regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
}
if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
return i;
} else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
return i;
} else if (!strict && this._monthsParse[i].test(monthName)) {
return i;
}
}
}
function setMonth (mom, value) {
var dayOfMonth;
if (typeof value === 'string') {
value = mom.localeData().monthsParse(value);
if (typeof value !== 'number') {
return mom;
}
}
dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
return mom;
}
function getSetMonth (value) {
if (value != null) {
setMonth(this, value);
utils_hooks__hooks.updateOffset(this, true);
return this;
} else {
return get_set__get(this, 'Month');
}
}
function getDaysInMonth () {
return daysInMonth(this.year(), this.month());
}
function checkOverflow (m) {
var overflow;
var a = m._a;
if (a && getParsingFlags(m).overflow === -2) {
overflow =
a[MONTH] < 0 || a[MONTH] > 11 ? MONTH :
a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE :
a[SECOND] < 0 || a[SECOND] > 59 ? SECOND :
a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
-1;
if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
overflow = DATE;
}
getParsingFlags(m).overflow = overflow;
}
return m;
}
function warn(msg) {
if (utils_hooks__hooks.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) {
console.warn('Deprecation warning: ' + msg);
}
}
function deprecate(msg, fn) {
var firstTime = true;
return extend(function () {
if (firstTime) {
warn(msg + '\n' + (new Error()).stack);
firstTime = false;
}
return fn.apply(this, arguments);
}, fn);
}
var deprecations = {};
function deprecateSimple(name, msg) {
if (!deprecations[name]) {
warn(msg);
deprecations[name] = true;
}
}
utils_hooks__hooks.suppressDeprecationWarnings = false;
var from_string__isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
var isoDates = [
['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
['GGGG-[W]WW', /\d{4}-W\d{2}/],
['YYYY-DDD', /\d{4}-\d{3}/]
];
var isoTimes = [
['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/],
['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
['HH:mm', /(T| )\d\d:\d\d/],
['HH', /(T| )\d\d/]
];
var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;
function configFromISO(config) {
var i, l,
string = config._i,
match = from_string__isoRegex.exec(string);
if (match) {
getParsingFlags(config).iso = true;
for (i = 0, l = isoDates.length; i < l; i++) {
if (isoDates[i][1].exec(string)) {
config._f = isoDates[i][0];
break;
}
}
for (i = 0, l = isoTimes.length; i < l; i++) {
if (isoTimes[i][1].exec(string)) {
config._f += (match[6] || ' ') + isoTimes[i][0];
break;
}
}
if (string.match(matchOffset)) {
config._f += 'Z';
}
configFromStringAndFormat(config);
} else {
config._isValid = false;
}
}
function configFromString(config) {
var matched = aspNetJsonRegex.exec(config._i);
if (matched !== null) {
config._d = new Date(+matched[1]);
return;
}
configFromISO(config);
if (config._isValid === false) {
delete config._isValid;
utils_hooks__hooks.createFromInputFallback(config);
}
}
utils_hooks__hooks.createFromInputFallback = deprecate(
'moment construction falls back to js Date. This is ' +
'discouraged and will be removed in upcoming major ' +
'release. Please refer to ' +
'https://github.com/moment/moment/issues/1407 for more info.',
function (config) {
config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
}
);
function createDate (y, m, d, h, M, s, ms) {
var date = new Date(y, m, d, h, M, s, ms);
if (y < 1970) {
date.setFullYear(y);
}
return date;
}
function createUTCDate (y) {
var date = new Date(Date.UTC.apply(null, arguments));
if (y < 1970) {
date.setUTCFullYear(y);
}
return date;
}
addFormatToken(0, ['YY', 2], 0, function () {
return this.year() % 100;
});
addFormatToken(0, ['YYYY', 4], 0, 'year');
addFormatToken(0, ['YYYYY', 5], 0, 'year');
addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
addUnitAlias('year', 'y');
addRegexToken('Y', matchSigned);
addRegexToken('YY', match1to2, match2);
addRegexToken('YYYY', match1to4, match4);
addRegexToken('YYYYY', match1to6, match6);
addRegexToken('YYYYYY', match1to6, match6);
addParseToken(['YYYYY', 'YYYYYY'], YEAR);
addParseToken('YYYY', function (input, array) {
array[YEAR] = input.length === 2 ? utils_hooks__hooks.parseTwoDigitYear(input) : toInt(input);
});
addParseToken('YY', function (input, array) {
array[YEAR] = utils_hooks__hooks.parseTwoDigitYear(input);
});
function daysInYear(year) {
return isLeapYear(year) ? 366 : 365;
}
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
utils_hooks__hooks.parseTwoDigitYear = function (input) {
return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
};
var getSetYear = makeGetSet('FullYear', false);
function getIsLeapYear () {
return isLeapYear(this.year());
}
addFormatToken('w', ['ww', 2], 'wo', 'week');
addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
addUnitAlias('week', 'w');
addUnitAlias('isoWeek', 'W');
addRegexToken('w', match1to2);
addRegexToken('ww', match1to2, match2);
addRegexToken('W', match1to2);
addRegexToken('WW', match1to2, match2);
addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
week[token.substr(0, 1)] = toInt(input);
});
function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
var end = firstDayOfWeekOfYear - firstDayOfWeek,
daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
adjustedMoment;
if (daysToDayOfWeek > end) {
daysToDayOfWeek -= 7;
}
if (daysToDayOfWeek < end - 7) {
daysToDayOfWeek += 7;
}
adjustedMoment = local__createLocal(mom).add(daysToDayOfWeek, 'd');
return {
week: Math.ceil(adjustedMoment.dayOfYear() / 7),
year: adjustedMoment.year()
};
}
function localeWeek (mom) {
return weekOfYear(mom, this._week.dow, this._week.doy).week;
}
var defaultLocaleWeek = {
dow : 0, // Sunday is the first day of the week.
doy : 6 // The week that contains Jan 1st is the first week of the year.
};
function localeFirstDayOfWeek () {
return this._week.dow;
}
function localeFirstDayOfYear () {
return this._week.doy;
}
function getSetWeek (input) {
var week = this.localeData().week(this);
return input == null ? week : this.add((input - week) * 7, 'd');
}
function getSetISOWeek (input) {
var week = weekOfYear(this, 1, 4).week;
return input == null ? week : this.add((input - week) * 7, 'd');
}
addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
addUnitAlias('dayOfYear', 'DDD');
addRegexToken('DDD', match1to3);
addRegexToken('DDDD', match3);
addParseToken(['DDD', 'DDDD'], function (input, array, config) {
config._dayOfYear = toInt(input);
});
function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
var week1Jan = 6 + firstDayOfWeek - firstDayOfWeekOfYear, janX = createUTCDate(year, 0, 1 + week1Jan), d = janX.getUTCDay(), dayOfYear;
if (d < firstDayOfWeek) {
d += 7;
}
weekday = weekday != null ? 1 * weekday : firstDayOfWeek;
dayOfYear = 1 + week1Jan + 7 * (week - 1) - d + weekday;
return {
year: dayOfYear > 0 ? year : year - 1,
dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
};
}
function getSetDayOfYear (input) {
var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
}
function defaults(a, b, c) {
if (a != null) {
return a;
}
if (b != null) {
return b;
}
return c;
}
function currentDateArray(config) {
var now = new Date();
if (config._useUTC) {
return [now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()];
}
return [now.getFullYear(), now.getMonth(), now.getDate()];
}
function configFromArray (config) {
var i, date, input = [], currentDate, yearToUse;
if (config._d) {
return;
}
currentDate = currentDateArray(config);
if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
dayOfYearFromWeekInfo(config);
}
if (config._dayOfYear) {
yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
if (config._dayOfYear > daysInYear(yearToUse)) {
getParsingFlags(config)._overflowDayOfYear = true;
}
date = createUTCDate(yearToUse, 0, config._dayOfYear);
config._a[MONTH] = date.getUTCMonth();
config._a[DATE] = date.getUTCDate();
}
for (i = 0; i < 3 && config._a[i] == null; ++i) {
config._a[i] = input[i] = currentDate[i];
}
for (; i < 7; i++) {
config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
}
if (config._a[HOUR] === 24 &&
config._a[MINUTE] === 0 &&
config._a[SECOND] === 0 &&
config._a[MILLISECOND] === 0) {
config._nextDay = true;
config._a[HOUR] = 0;
}
config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
if (config._tzm != null) {
config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
}
if (config._nextDay) {
config._a[HOUR] = 24;
}
}
function dayOfYearFromWeekInfo(config) {
var w, weekYear, week, weekday, dow, doy, temp;
w = config._w;
if (w.GG != null || w.W != null || w.E != null) {
dow = 1;
doy = 4;
weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(local__createLocal(), 1, 4).year);
week = defaults(w.W, 1);
weekday = defaults(w.E, 1);
} else {
dow = config._locale._week.dow;
doy = config._locale._week.doy;
weekYear = defaults(w.gg, config._a[YEAR], weekOfYear(local__createLocal(), dow, doy).year);
week = defaults(w.w, 1);
if (w.d != null) {
weekday = w.d;
if (weekday < dow) {
++week;
}
} else if (w.e != null) {
weekday = w.e + dow;
} else {
weekday = dow;
}
}
temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow);
config._a[YEAR] = temp.year;
config._dayOfYear = temp.dayOfYear;
}
utils_hooks__hooks.ISO_8601 = function () {};
function configFromStringAndFormat(config) {
if (config._f === utils_hooks__hooks.ISO_8601) {
configFromISO(config);
return;
}
config._a = [];
getParsingFlags(config).empty = true;
var string = '' + config._i,
i, parsedInput, tokens, token, skipped,
stringLength = string.length,
totalParsedInputLength = 0;
tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
for (i = 0; i < tokens.length; i++) {
token = tokens[i];
parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
if (parsedInput) {
skipped = string.substr(0, string.indexOf(parsedInput));
if (skipped.length > 0) {
getParsingFlags(config).unusedInput.push(skipped);
}
string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
totalParsedInputLength += parsedInput.length;
}
if (formatTokenFunctions[token]) {
if (parsedInput) {
getParsingFlags(config).empty = false;
}
else {
getParsingFlags(config).unusedTokens.push(token);
}
addTimeToArrayFromToken(token, parsedInput, config);
}
else if (config._strict && !parsedInput) {
getParsingFlags(config).unusedTokens.push(token);
}
}
getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
if (string.length > 0) {
getParsingFlags(config).unusedInput.push(string);
}
if (getParsingFlags(config).bigHour === true &&
config._a[HOUR] <= 12 &&
config._a[HOUR] > 0) {
getParsingFlags(config).bigHour = undefined;
}
config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
configFromArray(config);
checkOverflow(config);
}
function meridiemFixWrap (locale, hour, meridiem) {
var isPm;
if (meridiem == null) {
return hour;
}
if (locale.meridiemHour != null) {
return locale.meridiemHour(hour, meridiem);
} else if (locale.isPM != null) {
isPm = locale.isPM(meridiem);
if (isPm && hour < 12) {
hour += 12;
}
if (!isPm && hour === 12) {
hour = 0;
}
return hour;
} else {
return hour;
}
}
function configFromStringAndArray(config) {
var tempConfig,
bestMoment,
scoreToBeat,
i,
currentScore;
if (config._f.length === 0) {
getParsingFlags(config).invalidFormat = true;
config._d = new Date(NaN);
return;
}
for (i = 0; i < config._f.length; i++) {
currentScore = 0;
tempConfig = copyConfig({}, config);
if (config._useUTC != null) {
tempConfig._useUTC = config._useUTC;
}
tempConfig._f = config._f[i];
configFromStringAndFormat(tempConfig);
if (!valid__isValid(tempConfig)) {
continue;
}
currentScore += getParsingFlags(tempConfig).charsLeftOver;
currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
getParsingFlags(tempConfig).score = currentScore;
if (scoreToBeat == null || currentScore < scoreToBeat) {
scoreToBeat = currentScore;
bestMoment = tempConfig;
}
}
extend(config, bestMoment || tempConfig);
}
function configFromObject(config) {
if (config._d) {
return;
}
var i = normalizeObjectUnits(config._i);
config._a = [i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond];
configFromArray(config);
}
function createFromConfig (config) {
var res = new Moment(checkOverflow(prepareConfig(config)));
if (res._nextDay) {
res.add(1, 'd');
res._nextDay = undefined;
}
return res;
}
function prepareConfig (config) {
var input = config._i,
format = config._f;
config._locale = config._locale || locale_locales__getLocale(config._l);
if (input === null || (format === undefined && input === '')) {
return valid__createInvalid({nullInput: true});
}
if (typeof input === 'string') {
config._i = input = config._locale.preparse(input);
}
if (isMoment(input)) {
return new Moment(checkOverflow(input));
} else if (isArray(format)) {
configFromStringAndArray(config);
} else if (format) {
configFromStringAndFormat(config);
} else if (isDate(input)) {
config._d = input;
} else {
configFromInput(config);
}
return config;
}
function configFromInput(config) {
var input = config._i;
if (input === undefined) {
config._d = new Date();
} else if (isDate(input)) {
config._d = new Date(+input);
} else if (typeof input === 'string') {
configFromString(config);
} else if (isArray(input)) {
config._a = map(input.slice(0), function (obj) {
return parseInt(obj, 10);
});
configFromArray(config);
} else if (typeof(input) === 'object') {
configFromObject(config);
} else if (typeof(input) === 'number') {
config._d = new Date(input);
} else {
utils_hooks__hooks.createFromInputFallback(config);
}
}
function createLocalOrUTC (input, format, locale, strict, isUTC) {
var c = {};
if (typeof(locale) === 'boolean') {
strict = locale;
locale = undefined;
}
c._isAMomentObject = true;
c._useUTC = c._isUTC = isUTC;
c._l = locale;
c._i = input;
c._f = format;
c._strict = strict;
return createFromConfig(c);
}
function local__createLocal (input, format, locale, strict) {
return createLocalOrUTC(input, format, locale, strict, false);
}
var prototypeMin = deprecate(
'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548',
function () {
var other = local__createLocal.apply(null, arguments);
return other < this ? this : other;
}
);
var prototypeMax = deprecate(
'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548',
function () {
var other = local__createLocal.apply(null, arguments);
return other > this ? this : other;
}
);
function pickBy(fn, moments) {
var res, i;
if (moments.length === 1 && isArray(moments[0])) {
moments = moments[0];
}
if (!moments.length) {
return local__createLocal();
}
res = moments[0];
for (i = 1; i < moments.length; ++i) {
if (!moments[i].isValid() || moments[i][fn](res)) {
res = moments[i];
}
}
return res;
}
function min () {
var args = [].slice.call(arguments, 0);
return pickBy('isBefore', args);
}
function max () {
var args = [].slice.call(arguments, 0);
return pickBy('isAfter', args);
}
function Duration (duration) {
var normalizedInput = normalizeObjectUnits(duration),
years = normalizedInput.year || 0,
quarters = normalizedInput.quarter || 0,
months = normalizedInput.month || 0,
weeks = normalizedInput.week || 0,
days = normalizedInput.day || 0,
hours = normalizedInput.hour || 0,
minutes = normalizedInput.minute || 0,
seconds = normalizedInput.second || 0,
milliseconds = normalizedInput.millisecond || 0;
this._milliseconds = +milliseconds +
seconds * 1e3 + // 1000
minutes * 6e4 + // 1000 * 60
hours * 36e5; // 1000 * 60 * 60
this._days = +days +
weeks * 7;
this._months = +months +
quarters * 3 +
years * 12;
this._data = {};
this._locale = locale_locales__getLocale();
this._bubble();
}
function isDuration (obj) {
return obj instanceof Duration;
}
function offset (token, separator) {
addFormatToken(token, 0, 0, function () {
var offset = this.utcOffset();
var sign = '+';
if (offset < 0) {
offset = -offset;
sign = '-';
}
return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
});
}
offset('Z', ':');
offset('ZZ', '');
addRegexToken('Z', matchOffset);
addRegexToken('ZZ', matchOffset);
addParseToken(['Z', 'ZZ'], function (input, array, config) {
config._useUTC = true;
config._tzm = offsetFromString(input);
});
var chunkOffset = /([\+\-]|\d\d)/gi;
function offsetFromString(string) {
var matches = ((string || '').match(matchOffset) || []);
var chunk = matches[matches.length - 1] || [];
var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
var minutes = +(parts[1] * 60) + toInt(parts[2]);
return parts[0] === '+' ? minutes : -minutes;
}
function cloneWithOffset(input, model) {
var res, diff;
if (model._isUTC) {
res = model.clone();
diff = (isMoment(input) || isDate(input) ? +input : +local__createLocal(input)) - (+res);
res._d.setTime(+res._d + diff);
utils_hooks__hooks.updateOffset(res, false);
return res;
} else {
return local__createLocal(input).local();
}
}
function getDateOffset (m) {
return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
}
utils_hooks__hooks.updateOffset = function () {};
function getSetOffset (input, keepLocalTime) {
var offset = this._offset || 0,
localAdjust;
if (input != null) {
if (typeof input === 'string') {
input = offsetFromString(input);
}
if (Math.abs(input) < 16) {
input = input * 60;
}
if (!this._isUTC && keepLocalTime) {
localAdjust = getDateOffset(this);
}
this._offset = input;
this._isUTC = true;
if (localAdjust != null) {
this.add(localAdjust, 'm');
}
if (offset !== input) {
if (!keepLocalTime || this._changeInProgress) {
add_subtract__addSubtract(this, create__createDuration(input - offset, 'm'), 1, false);
} else if (!this._changeInProgress) {
this._changeInProgress = true;
utils_hooks__hooks.updateOffset(this, true);
this._changeInProgress = null;
}
}
return this;
} else {
return this._isUTC ? offset : getDateOffset(this);
}
}
function getSetZone (input, keepLocalTime) {
if (input != null) {
if (typeof input !== 'string') {
input = -input;
}
this.utcOffset(input, keepLocalTime);
return this;
} else {
return -this.utcOffset();
}
}
function setOffsetToUTC (keepLocalTime) {
return this.utcOffset(0, keepLocalTime);
}
function setOffsetToLocal (keepLocalTime) {
if (this._isUTC) {
this.utcOffset(0, keepLocalTime);
this._isUTC = false;
if (keepLocalTime) {
this.subtract(getDateOffset(this), 'm');
}
}
return this;
}
function setOffsetToParsedOffset () {
if (this._tzm) {
this.utcOffset(this._tzm);
} else if (typeof this._i === 'string') {
this.utcOffset(offsetFromString(this._i));
}
return this;
}
function hasAlignedHourOffset (input) {
input = input ? local__createLocal(input).utcOffset() : 0;
return (this.utcOffset() - input) % 60 === 0;
}
function isDaylightSavingTime () {
return (
this.utcOffset() > this.clone().month(0).utcOffset() ||
this.utcOffset() > this.clone().month(5).utcOffset()
);
}
function isDaylightSavingTimeShifted () {
if (typeof this._isDSTShifted !== 'undefined') {
return this._isDSTShifted;
}
var c = {};
copyConfig(c, this);
c = prepareConfig(c);
if (c._a) {
var other = c._isUTC ? create_utc__createUTC(c._a) : local__createLocal(c._a);
this._isDSTShifted = this.isValid() &&
compareArrays(c._a, other.toArray()) > 0;
} else {
this._isDSTShifted = false;
}
return this._isDSTShifted;
}
function isLocal () {
return !this._isUTC;
}
function isUtcOffset () {
return this._isUTC;
}
function isUtc () {
return this._isUTC && this._offset === 0;
}
var aspNetRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/;
var create__isoRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/;
function create__createDuration (input, key) {
var duration = input,
match = null,
sign,
ret,
diffRes;
if (isDuration(input)) {
duration = {
ms : input._milliseconds,
d : input._days,
M : input._months
};
} else if (typeof input === 'number') {
duration = {};
if (key) {
duration[key] = input;
} else {
duration.milliseconds = input;
}
} else if (!!(match = aspNetRegex.exec(input))) {
sign = (match[1] === '-') ? -1 : 1;
duration = {
y : 0,
d : toInt(match[DATE]) * sign,
h : toInt(match[HOUR]) * sign,
m : toInt(match[MINUTE]) * sign,
s : toInt(match[SECOND]) * sign,
ms : toInt(match[MILLISECOND]) * sign
};
} else if (!!(match = create__isoRegex.exec(input))) {
sign = (match[1] === '-') ? -1 : 1;
duration = {
y : parseIso(match[2], sign),
M : parseIso(match[3], sign),
d : parseIso(match[4], sign),
h : parseIso(match[5], sign),
m : parseIso(match[6], sign),
s : parseIso(match[7], sign),
w : parseIso(match[8], sign)
};
} else if (duration == null) {// checks for null or undefined
duration = {};
} else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
diffRes = momentsDifference(local__createLocal(duration.from), local__createLocal(duration.to));
duration = {};
duration.ms = diffRes.milliseconds;
duration.M = diffRes.months;
}
ret = new Duration(duration);
if (isDuration(input) && hasOwnProp(input, '_locale')) {
ret._locale = input._locale;
}
return ret;
}
create__createDuration.fn = Duration.prototype;
function parseIso (inp, sign) {
var res = inp && parseFloat(inp.replace(',', '.'));
return (isNaN(res) ? 0 : res) * sign;
}
function positiveMomentsDifference(base, other) {
var res = {milliseconds: 0, months: 0};
res.months = other.month() - base.month() +
(other.year() - base.year()) * 12;
if (base.clone().add(res.months, 'M').isAfter(other)) {
--res.months;
}
res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
return res;
}
function momentsDifference(base, other) {
var res;
other = cloneWithOffset(other, base);
if (base.isBefore(other)) {
res = positiveMomentsDifference(base, other);
} else {
res = positiveMomentsDifference(other, base);
res.milliseconds = -res.milliseconds;
res.months = -res.months;
}
return res;
}
function createAdder(direction, name) {
return function (val, period) {
var dur, tmp;
if (period !== null && !isNaN(+period)) {
deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period).');
tmp = val; val = period; period = tmp;
}
val = typeof val === 'string' ? +val : val;
dur = create__createDuration(val, period);
add_subtract__addSubtract(this, dur, direction);
return this;
};
}
function add_subtract__addSubtract (mom, duration, isAdding, updateOffset) {
var milliseconds = duration._milliseconds,
days = duration._days,
months = duration._months;
updateOffset = updateOffset == null ? true : updateOffset;
if (milliseconds) {
mom._d.setTime(+mom._d + milliseconds * isAdding);
}
if (days) {
get_set__set(mom, 'Date', get_set__get(mom, 'Date') + days * isAdding);
}
if (months) {
setMonth(mom, get_set__get(mom, 'Month') + months * isAdding);
}
if (updateOffset) {
utils_hooks__hooks.updateOffset(mom, days || months);
}
}
var add_subtract__add = createAdder(1, 'add');
var add_subtract__subtract = createAdder(-1, 'subtract');
function moment_calendar__calendar (time, formats) {
var now = time || local__createLocal(),
sod = cloneWithOffset(now, this).startOf('day'),
diff = this.diff(sod, 'days', true),
format = diff < -6 ? 'sameElse' :
diff < -1 ? 'lastWeek' :
diff < 0 ? 'lastDay' :
diff < 1 ? 'sameDay' :
diff < 2 ? 'nextDay' :
diff < 7 ? 'nextWeek' : 'sameElse';
return this.format(formats && formats[format] || this.localeData().calendar(format, this, local__createLocal(now)));
}
function clone () {
return new Moment(this);
}
function isAfter (input, units) {
var inputMs;
units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond');
if (units === 'millisecond') {
input = isMoment(input) ? input : local__createLocal(input);
return +this > +input;
} else {
inputMs = isMoment(input) ? +input : +local__createLocal(input);
return inputMs < +this.clone().startOf(units);
}
}
function isBefore (input, units) {
var inputMs;
units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond');
if (units === 'millisecond') {
input = isMoment(input) ? input : local__createLocal(input);
return +this < +input;
} else {
inputMs = isMoment(input) ? +input : +local__createLocal(input);
return +this.clone().endOf(units) < inputMs;
}
}
function isBetween (from, to, units) {
return this.isAfter(from, units) && this.isBefore(to, units);
}
function isSame (input, units) {
var inputMs;
units = normalizeUnits(units || 'millisecond');
if (units === 'millisecond') {
input = isMoment(input) ? input : local__createLocal(input);
return +this === +input;
} else {
inputMs = +local__createLocal(input);
return +(this.clone().startOf(units)) <= inputMs && inputMs <= +(this.clone().endOf(units));
}
}
function diff (input, units, asFloat) {
var that = cloneWithOffset(input, this),
zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4,
delta, output;
units = normalizeUnits(units);
if (units === 'year' || units === 'month' || units === 'quarter') {
output = monthDiff(this, that);
if (units === 'quarter') {
output = output / 3;
} else if (units === 'year') {
output = output / 12;
}
} else {
delta = this - that;
output = units === 'second' ? delta / 1e3 : // 1000
units === 'minute' ? delta / 6e4 : // 1000 * 60
units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60
units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
delta;
}
return asFloat ? output : absFloor(output);
}
function monthDiff (a, b) {
var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
anchor = a.clone().add(wholeMonthDiff, 'months'),
anchor2, adjust;
if (b - anchor < 0) {
anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
adjust = (b - anchor) / (anchor - anchor2);
} else {
anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
adjust = (b - anchor) / (anchor2 - anchor);
}
return -(wholeMonthDiff + adjust);
}
utils_hooks__hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
function toString () {
return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
}
function moment_format__toISOString () {
var m = this.clone().utc();
if (0 < m.year() && m.year() <= 9999) {
if ('function' === typeof Date.prototype.toISOString) {
return this.toDate().toISOString();
} else {
return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
}
} else {
return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
}
}
function format (inputString) {
var output = formatMoment(this, inputString || utils_hooks__hooks.defaultFormat);
return this.localeData().postformat(output);
}
function from (time, withoutSuffix) {
if (!this.isValid()) {
return this.localeData().invalidDate();
}
return create__createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
}
function fromNow (withoutSuffix) {
return this.from(local__createLocal(), withoutSuffix);
}
function to (time, withoutSuffix) {
if (!this.isValid()) {
return this.localeData().invalidDate();
}
return create__createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix);
}
function toNow (withoutSuffix) {
return this.to(local__createLocal(), withoutSuffix);
}
function locale (key) {
var newLocaleData;
if (key === undefined) {
return this._locale._abbr;
} else {
newLocaleData = locale_locales__getLocale(key);
if (newLocaleData != null) {
this._locale = newLocaleData;
}
return this;
}
}
var lang = deprecate(
'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
function (key) {
if (key === undefined) {
return this.localeData();
} else {
return this.locale(key);
}
}
);
function localeData () {
return this._locale;
}
function startOf (units) {
units = normalizeUnits(units);
switch (units) {
case 'year':
this.month(0);
/* falls through */
case 'quarter':
case 'month':
this.date(1);
/* falls through */
case 'week':
case 'isoWeek':
case 'day':
this.hours(0);
/* falls through */
case 'hour':
this.minutes(0);
/* falls through */
case 'minute':
this.seconds(0);
/* falls through */
case 'second':
this.milliseconds(0);
}
if (units === 'week') {
this.weekday(0);
}
if (units === 'isoWeek') {
this.isoWeekday(1);
}
if (units === 'quarter') {
this.month(Math.floor(this.month() / 3) * 3);
}
return this;
}
function endOf (units) {
units = normalizeUnits(units);
if (units === undefined || units === 'millisecond') {
return this;
}
return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
}
function to_type__valueOf () {
return +this._d - ((this._offset || 0) * 60000);
}
function unix () {
return Math.floor(+this / 1000);
}
function toDate () {
return this._offset ? new Date(+this) : this._d;
}
function toArray () {
var m = this;
return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
}
function toObject () {
var m = this;
return {
years: m.year(),
months: m.month(),
date: m.date(),
hours: m.hours(),
minutes: m.minutes(),
seconds: m.seconds(),
milliseconds: m.milliseconds()
};
}
function moment_valid__isValid () {
return valid__isValid(this);
}
function parsingFlags () {
return extend({}, getParsingFlags(this));
}
function invalidAt () {
return getParsingFlags(this).overflow;
}
addFormatToken(0, ['gg', 2], 0, function () {
return this.weekYear() % 100;
});
addFormatToken(0, ['GG', 2], 0, function () {
return this.isoWeekYear() % 100;
});
function addWeekYearFormatToken (token, getter) {
addFormatToken(0, [token, token.length], 0, getter);
}
addWeekYearFormatToken('gggg', 'weekYear');
addWeekYearFormatToken('ggggg', 'weekYear');
addWeekYearFormatToken('GGGG', 'isoWeekYear');
addWeekYearFormatToken('GGGGG', 'isoWeekYear');
addUnitAlias('weekYear', 'gg');
addUnitAlias('isoWeekYear', 'GG');
addRegexToken('G', matchSigned);
addRegexToken('g', matchSigned);
addRegexToken('GG', match1to2, match2);
addRegexToken('gg', match1to2, match2);
addRegexToken('GGGG', match1to4, match4);
addRegexToken('gggg', match1to4, match4);
addRegexToken('GGGGG', match1to6, match6);
addRegexToken('ggggg', match1to6, match6);
addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
week[token.substr(0, 2)] = toInt(input);
});
addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
week[token] = utils_hooks__hooks.parseTwoDigitYear(input);
});
function weeksInYear(year, dow, doy) {
return weekOfYear(local__createLocal([year, 11, 31 + dow - doy]), dow, doy).week;
}
function getSetWeekYear (input) {
var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year;
return input == null ? year : this.add((input - year), 'y');
}
function getSetISOWeekYear (input) {
var year = weekOfYear(this, 1, 4).year;
return input == null ? year : this.add((input - year), 'y');
}
function getISOWeeksInYear () {
return weeksInYear(this.year(), 1, 4);
}
function getWeeksInYear () {
var weekInfo = this.localeData()._week;
return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
}
addFormatToken('Q', 0, 0, 'quarter');
addUnitAlias('quarter', 'Q');
addRegexToken('Q', match1);
addParseToken('Q', function (input, array) {
array[MONTH] = (toInt(input) - 1) * 3;
});
function getSetQuarter (input) {
return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
}
addFormatToken('D', ['DD', 2], 'Do', 'date');
addUnitAlias('date', 'D');
addRegexToken('D', match1to2);
addRegexToken('DD', match1to2, match2);
addRegexToken('Do', function (isStrict, locale) {
return isStrict ? locale._ordinalParse : locale._ordinalParseLenient;
});
addParseToken(['D', 'DD'], DATE);
addParseToken('Do', function (input, array) {
array[DATE] = toInt(input.match(match1to2)[0], 10);
});
var getSetDayOfMonth = makeGetSet('Date', true);
addFormatToken('d', 0, 'do', 'day');
addFormatToken('dd', 0, 0, function (format) {
return this.localeData().weekdaysMin(this, format);
});
addFormatToken('ddd', 0, 0, function (format) {
return this.localeData().weekdaysShort(this, format);
});
addFormatToken('dddd', 0, 0, function (format) {
return this.localeData().weekdays(this, format);
});
addFormatToken('e', 0, 0, 'weekday');
addFormatToken('E', 0, 0, 'isoWeekday');
addUnitAlias('day', 'd');
addUnitAlias('weekday', 'e');
addUnitAlias('isoWeekday', 'E');
addRegexToken('d', match1to2);
addRegexToken('e', match1to2);
addRegexToken('E', match1to2);
addRegexToken('dd', matchWord);
addRegexToken('ddd', matchWord);
addRegexToken('dddd', matchWord);
addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config) {
var weekday = config._locale.weekdaysParse(input);
if (weekday != null) {
week.d = weekday;
} else {
getParsingFlags(config).invalidWeekday = input;
}
});
addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
week[token] = toInt(input);
});
function parseWeekday(input, locale) {
if (typeof input !== 'string') {
return input;
}
if (!isNaN(input)) {
return parseInt(input, 10);
}
input = locale.weekdaysParse(input);
if (typeof input === 'number') {
return input;
}
return null;
}
var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
function localeWeekdays (m) {
return this._weekdays[m.day()];
}
var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
function localeWeekdaysShort (m) {
return this._weekdaysShort[m.day()];
}
var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
function localeWeekdaysMin (m) {
return this._weekdaysMin[m.day()];
}
function localeWeekdaysParse (weekdayName) {
var i, mom, regex;
this._weekdaysParse = this._weekdaysParse || [];
for (i = 0; i < 7; i++) {
if (!this._weekdaysParse[i]) {
mom = local__createLocal([2000, 1]).day(i);
regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
}
if (this._weekdaysParse[i].test(weekdayName)) {
return i;
}
}
}
function getSetDayOfWeek (input) {
var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
if (input != null) {
input = parseWeekday(input, this.localeData());
return this.add(input - day, 'd');
} else {
return day;
}
}
function getSetLocaleDayOfWeek (input) {
var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
return input == null ? weekday : this.add(input - weekday, 'd');
}
function getSetISODayOfWeek (input) {
return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
}
addFormatToken('H', ['HH', 2], 0, 'hour');
addFormatToken('h', ['hh', 2], 0, function () {
return this.hours() % 12 || 12;
});
function meridiem (token, lowercase) {
addFormatToken(token, 0, 0, function () {
return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
});
}
meridiem('a', true);
meridiem('A', false);
addUnitAlias('hour', 'h');
function matchMeridiem (isStrict, locale) {
return locale._meridiemParse;
}
addRegexToken('a', matchMeridiem);
addRegexToken('A', matchMeridiem);
addRegexToken('H', match1to2);
addRegexToken('h', match1to2);
addRegexToken('HH', match1to2, match2);
addRegexToken('hh', match1to2, match2);
addParseToken(['H', 'HH'], HOUR);
addParseToken(['a', 'A'], function (input, array, config) {
config._isPm = config._locale.isPM(input);
config._meridiem = input;
});
addParseToken(['h', 'hh'], function (input, array, config) {
array[HOUR] = toInt(input);
getParsingFlags(config).bigHour = true;
});
function localeIsPM (input) {
return ((input + '').toLowerCase().charAt(0) === 'p');
}
var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
function localeMeridiem (hours, minutes, isLower) {
if (hours > 11) {
return isLower ? 'pm' : 'PM';
} else {
return isLower ? 'am' : 'AM';
}
}
var getSetHour = makeGetSet('Hours', true);
addFormatToken('m', ['mm', 2], 0, 'minute');
addUnitAlias('minute', 'm');
addRegexToken('m', match1to2);
addRegexToken('mm', match1to2, match2);
addParseToken(['m', 'mm'], MINUTE);
var getSetMinute = makeGetSet('Minutes', false);
addFormatToken('s', ['ss', 2], 0, 'second');
addUnitAlias('second', 's');
addRegexToken('s', match1to2);
addRegexToken('ss', match1to2, match2);
addParseToken(['s', 'ss'], SECOND);
var getSetSecond = makeGetSet('Seconds', false);
addFormatToken('S', 0, 0, function () {
return ~~(this.millisecond() / 100);
});
addFormatToken(0, ['SS', 2], 0, function () {
return ~~(this.millisecond() / 10);
});
addFormatToken(0, ['SSS', 3], 0, 'millisecond');
addFormatToken(0, ['SSSS', 4], 0, function () {
return this.millisecond() * 10;
});
addFormatToken(0, ['SSSSS', 5], 0, function () {
return this.millisecond() * 100;
});
addFormatToken(0, ['SSSSSS', 6], 0, function () {
return this.millisecond() * 1000;
});
addFormatToken(0, ['SSSSSSS', 7], 0, function () {
return this.millisecond() * 10000;
});
addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
return this.millisecond() * 100000;
});
addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
return this.millisecond() * 1000000;
});
addUnitAlias('millisecond', 'ms');
addRegexToken('S', match1to3, match1);
addRegexToken('SS', match1to3, match2);
addRegexToken('SSS', match1to3, match3);
var token;
for (token = 'SSSS'; token.length <= 9; token += 'S') {
addRegexToken(token, matchUnsigned);
}
function parseMs(input, array) {
array[MILLISECOND] = toInt(('0.' + input) * 1000);
}
for (token = 'S'; token.length <= 9; token += 'S') {
addParseToken(token, parseMs);
}
var getSetMillisecond = makeGetSet('Milliseconds', false);
addFormatToken('z', 0, 0, 'zoneAbbr');
addFormatToken('zz', 0, 0, 'zoneName');
function getZoneAbbr () {
return this._isUTC ? 'UTC' : '';
}
function getZoneName () {
return this._isUTC ? 'Coordinated Universal Time' : '';
}
var momentPrototype__proto = Moment.prototype;
momentPrototype__proto.add = add_subtract__add;
momentPrototype__proto.calendar = moment_calendar__calendar;
momentPrototype__proto.clone = clone;
momentPrototype__proto.diff = diff;
momentPrototype__proto.endOf = endOf;
momentPrototype__proto.format = format;
momentPrototype__proto.from = from;
momentPrototype__proto.fromNow = fromNow;
momentPrototype__proto.to = to;
momentPrototype__proto.toNow = toNow;
momentPrototype__proto.get = getSet;
momentPrototype__proto.invalidAt = invalidAt;
momentPrototype__proto.isAfter = isAfter;
momentPrototype__proto.isBefore = isBefore;
momentPrototype__proto.isBetween = isBetween;
momentPrototype__proto.isSame = isSame;
momentPrototype__proto.isValid = moment_valid__isValid;
momentPrototype__proto.lang = lang;
momentPrototype__proto.locale = locale;
momentPrototype__proto.localeData = localeData;
momentPrototype__proto.max = prototypeMax;
momentPrototype__proto.min = prototypeMin;
momentPrototype__proto.parsingFlags = parsingFlags;
momentPrototype__proto.set = getSet;
momentPrototype__proto.startOf = startOf;
momentPrototype__proto.subtract = add_subtract__subtract;
momentPrototype__proto.toArray = toArray;
momentPrototype__proto.toObject = toObject;
momentPrototype__proto.toDate = toDate;
momentPrototype__proto.toISOString = moment_format__toISOString;
momentPrototype__proto.toJSON = moment_format__toISOString;
momentPrototype__proto.toString = toString;
momentPrototype__proto.unix = unix;
momentPrototype__proto.valueOf = to_type__valueOf;
momentPrototype__proto.year = getSetYear;
momentPrototype__proto.isLeapYear = getIsLeapYear;
momentPrototype__proto.weekYear = getSetWeekYear;
momentPrototype__proto.isoWeekYear = getSetISOWeekYear;
momentPrototype__proto.quarter = momentPrototype__proto.quarters = getSetQuarter;
momentPrototype__proto.month = getSetMonth;
momentPrototype__proto.daysInMonth = getDaysInMonth;
momentPrototype__proto.week = momentPrototype__proto.weeks = getSetWeek;
momentPrototype__proto.isoWeek = momentPrototype__proto.isoWeeks = getSetISOWeek;
momentPrototype__proto.weeksInYear = getWeeksInYear;
momentPrototype__proto.isoWeeksInYear = getISOWeeksInYear;
momentPrototype__proto.date = getSetDayOfMonth;
momentPrototype__proto.day = momentPrototype__proto.days = getSetDayOfWeek;
momentPrototype__proto.weekday = getSetLocaleDayOfWeek;
momentPrototype__proto.isoWeekday = getSetISODayOfWeek;
momentPrototype__proto.dayOfYear = getSetDayOfYear;
momentPrototype__proto.hour = momentPrototype__proto.hours = getSetHour;
momentPrototype__proto.minute = momentPrototype__proto.minutes = getSetMinute;
momentPrototype__proto.second = momentPrototype__proto.seconds = getSetSecond;
momentPrototype__proto.millisecond = momentPrototype__proto.milliseconds = getSetMillisecond;
momentPrototype__proto.utcOffset = getSetOffset;
momentPrototype__proto.utc = setOffsetToUTC;
momentPrototype__proto.local = setOffsetToLocal;
momentPrototype__proto.parseZone = setOffsetToParsedOffset;
momentPrototype__proto.hasAlignedHourOffset = hasAlignedHourOffset;
momentPrototype__proto.isDST = isDaylightSavingTime;
momentPrototype__proto.isDSTShifted = isDaylightSavingTimeShifted;
momentPrototype__proto.isLocal = isLocal;
momentPrototype__proto.isUtcOffset = isUtcOffset;
momentPrototype__proto.isUtc = isUtc;
momentPrototype__proto.isUTC = isUtc;
momentPrototype__proto.zoneAbbr = getZoneAbbr;
momentPrototype__proto.zoneName = getZoneName;
momentPrototype__proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
momentPrototype__proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
momentPrototype__proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
momentPrototype__proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779', getSetZone);
var momentPrototype = momentPrototype__proto;
function moment__createUnix (input) {
return local__createLocal(input * 1000);
}
function moment__createInZone () {
return local__createLocal.apply(null, arguments).parseZone();
}
var defaultCalendar = {
sameDay : '[Today at] LT',
nextDay : '[Tomorrow at] LT',
nextWeek : 'dddd [at] LT',
lastDay : '[Yesterday at] LT',
lastWeek : '[Last] dddd [at] LT',
sameElse : 'L'
};
function locale_calendar__calendar (key, mom, now) {
var output = this._calendar[key];
return typeof output === 'function' ? output.call(mom, now) : output;
}
var defaultLongDateFormat = {
LTS : 'h:mm:ss A',
LT : 'h:mm A',
L : 'MM/DD/YYYY',
LL : 'MMMM D, YYYY',
LLL : 'MMMM D, YYYY h:mm A',
LLLL : 'dddd, MMMM D, YYYY h:mm A'
};
function longDateFormat (key) {
var format = this._longDateFormat[key],
formatUpper = this._longDateFormat[key.toUpperCase()];
if (format || !formatUpper) {
return format;
}
this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
return val.slice(1);
});
return this._longDateFormat[key];
}
var defaultInvalidDate = 'Invalid date';
function invalidDate () {
return this._invalidDate;
}
var defaultOrdinal = '%d';
var defaultOrdinalParse = /\d{1,2}/;
function ordinal (number) {
return this._ordinal.replace('%d', number);
}
function preParsePostFormat (string) {
return string;
}
var defaultRelativeTime = {
future : 'in %s',
past : '%s ago',
s : 'a few seconds',
m : 'a minute',
mm : '%d minutes',
h : 'an hour',
hh : '%d hours',
d : 'a day',
dd : '%d days',
M : 'a month',
MM : '%d months',
y : 'a year',
yy : '%d years'
};
function relative__relativeTime (number, withoutSuffix, string, isFuture) {
var output = this._relativeTime[string];
return (typeof output === 'function') ?
output(number, withoutSuffix, string, isFuture) :
output.replace(/%d/i, number);
}
function pastFuture (diff, output) {
var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
}
function locale_set__set (config) {
var prop, i;
for (i in config) {
prop = config[i];
if (typeof prop === 'function') {
this[i] = prop;
} else {
this['_' + i] = prop;
}
}
this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + (/\d{1,2}/).source);
}
var prototype__proto = Locale.prototype;
prototype__proto._calendar = defaultCalendar;
prototype__proto.calendar = locale_calendar__calendar;
prototype__proto._longDateFormat = defaultLongDateFormat;
prototype__proto.longDateFormat = longDateFormat;
prototype__proto._invalidDate = defaultInvalidDate;
prototype__proto.invalidDate = invalidDate;
prototype__proto._ordinal = defaultOrdinal;
prototype__proto.ordinal = ordinal;
prototype__proto._ordinalParse = defaultOrdinalParse;
prototype__proto.preparse = preParsePostFormat;
prototype__proto.postformat = preParsePostFormat;
prototype__proto._relativeTime = defaultRelativeTime;
prototype__proto.relativeTime = relative__relativeTime;
prototype__proto.pastFuture = pastFuture;
prototype__proto.set = locale_set__set;
prototype__proto.months = localeMonths;
prototype__proto._months = defaultLocaleMonths;
prototype__proto.monthsShort = localeMonthsShort;
prototype__proto._monthsShort = defaultLocaleMonthsShort;
prototype__proto.monthsParse = localeMonthsParse;
prototype__proto.week = localeWeek;
prototype__proto._week = defaultLocaleWeek;
prototype__proto.firstDayOfYear = localeFirstDayOfYear;
prototype__proto.firstDayOfWeek = localeFirstDayOfWeek;
prototype__proto.weekdays = localeWeekdays;
prototype__proto._weekdays = defaultLocaleWeekdays;
prototype__proto.weekdaysMin = localeWeekdaysMin;
prototype__proto._weekdaysMin = defaultLocaleWeekdaysMin;
prototype__proto.weekdaysShort = localeWeekdaysShort;
prototype__proto._weekdaysShort = defaultLocaleWeekdaysShort;
prototype__proto.weekdaysParse = localeWeekdaysParse;
prototype__proto.isPM = localeIsPM;
prototype__proto._meridiemParse = defaultLocaleMeridiemParse;
prototype__proto.meridiem = localeMeridiem;
function lists__get (format, index, field, setter) {
var locale = locale_locales__getLocale();
var utc = create_utc__createUTC().set(setter, index);
return locale[field](utc, format);
}
function list (format, index, field, count, setter) {
if (typeof format === 'number') {
index = format;
format = undefined;
}
format = format || '';
if (index != null) {
return lists__get(format, index, field, setter);
}
var i;
var out = [];
for (i = 0; i < count; i++) {
out[i] = lists__get(format, i, field, setter);
}
return out;
}
function lists__listMonths (format, index) {
return list(format, index, 'months', 12, 'month');
}
function lists__listMonthsShort (format, index) {
return list(format, index, 'monthsShort', 12, 'month');
}
function lists__listWeekdays (format, index) {
return list(format, index, 'weekdays', 7, 'day');
}
function lists__listWeekdaysShort (format, index) {
return list(format, index, 'weekdaysShort', 7, 'day');
}
function lists__listWeekdaysMin (format, index) {
return list(format, index, 'weekdaysMin', 7, 'day');
}
locale_locales__getSetGlobalLocale('en', {
ordinalParse: /\d{1,2}(th|st|nd|rd)/,
ordinal : function (number) {
var b = number % 10,
output = (toInt(number % 100 / 10) === 1) ? 'th' :
(b === 1) ? 'st' :
(b === 2) ? 'nd' :
(b === 3) ? 'rd' : 'th';
return number + output;
}
});
utils_hooks__hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', locale_locales__getSetGlobalLocale);
utils_hooks__hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', locale_locales__getLocale);
var mathAbs = Math.abs;
function duration_abs__abs () {
var data = this._data;
this._milliseconds = mathAbs(this._milliseconds);
this._days = mathAbs(this._days);
this._months = mathAbs(this._months);
data.milliseconds = mathAbs(data.milliseconds);
data.seconds = mathAbs(data.seconds);
data.minutes = mathAbs(data.minutes);
data.hours = mathAbs(data.hours);
data.months = mathAbs(data.months);
data.years = mathAbs(data.years);
return this;
}
function duration_add_subtract__addSubtract (duration, input, value, direction) {
var other = create__createDuration(input, value);
duration._milliseconds += direction * other._milliseconds;
duration._days += direction * other._days;
duration._months += direction * other._months;
return duration._bubble();
}
function duration_add_subtract__add (input, value) {
return duration_add_subtract__addSubtract(this, input, value, 1);
}
function duration_add_subtract__subtract (input, value) {
return duration_add_subtract__addSubtract(this, input, value, -1);
}
function absCeil (number) {
if (number < 0) {
return Math.floor(number);
} else {
return Math.ceil(number);
}
}
function bubble () {
var milliseconds = this._milliseconds;
var days = this._days;
var months = this._months;
var data = this._data;
var seconds, minutes, hours, years, monthsFromDays;
if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
(milliseconds <= 0 && days <= 0 && months <= 0))) {
milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
days = 0;
months = 0;
}
data.milliseconds = milliseconds % 1000;
seconds = absFloor(milliseconds / 1000);
data.seconds = seconds % 60;
minutes = absFloor(seconds / 60);
data.minutes = minutes % 60;
hours = absFloor(minutes / 60);
data.hours = hours % 24;
days += absFloor(hours / 24);
monthsFromDays = absFloor(daysToMonths(days));
months += monthsFromDays;
days -= absCeil(monthsToDays(monthsFromDays));
years = absFloor(months / 12);
months %= 12;
data.days = days;
data.months = months;
data.years = years;
return this;
}
function daysToMonths (days) {
return days * 4800 / 146097;
}
function monthsToDays (months) {
return months * 146097 / 4800;
}
function as (units) {
var days;
var months;
var milliseconds = this._milliseconds;
units = normalizeUnits(units);
if (units === 'month' || units === 'year') {
days = this._days + milliseconds / 864e5;
months = this._months + daysToMonths(days);
return units === 'month' ? months : months / 12;
} else {
days = this._days + Math.round(monthsToDays(this._months));
switch (units) {
case 'week' : return days / 7 + milliseconds / 6048e5;
case 'day' : return days + milliseconds / 864e5;
case 'hour' : return days * 24 + milliseconds / 36e5;
case 'minute' : return days * 1440 + milliseconds / 6e4;
case 'second' : return days * 86400 + milliseconds / 1000;
case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
default: throw new Error('Unknown unit ' + units);
}
}
}
function duration_as__valueOf () {
return (
this._milliseconds +
this._days * 864e5 +
(this._months % 12) * 2592e6 +
toInt(this._months / 12) * 31536e6
);
}
function makeAs (alias) {
return function () {
return this.as(alias);
};
}
var asMilliseconds = makeAs('ms');
var asSeconds = makeAs('s');
var asMinutes = makeAs('m');
var asHours = makeAs('h');
var asDays = makeAs('d');
var asWeeks = makeAs('w');
var asMonths = makeAs('M');
var asYears = makeAs('y');
function duration_get__get (units) {
units = normalizeUnits(units);
return this[units + 's']();
}
function makeGetter(name) {
return function () {
return this._data[name];
};
}
var milliseconds = makeGetter('milliseconds');
var seconds = makeGetter('seconds');
var minutes = makeGetter('minutes');
var hours = makeGetter('hours');
var days = makeGetter('days');
var months = makeGetter('months');
var years = makeGetter('years');
function weeks () {
return absFloor(this.days() / 7);
}
var round = Math.round;
var thresholds = {
s: 45, // seconds to minute
m: 45, // minutes to hour
h: 22, // hours to day
d: 26, // days to month
M: 11 // months to year
};
function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
}
function duration_humanize__relativeTime (posNegDuration, withoutSuffix, locale) {
var duration = create__createDuration(posNegDuration).abs();
var seconds = round(duration.as('s'));
var minutes = round(duration.as('m'));
var hours = round(duration.as('h'));
var days = round(duration.as('d'));
var months = round(duration.as('M'));
var years = round(duration.as('y'));
var a = seconds < thresholds.s && ['s', seconds] ||
minutes === 1 && ['m'] ||
minutes < thresholds.m && ['mm', minutes] ||
hours === 1 && ['h'] ||
hours < thresholds.h && ['hh', hours] ||
days === 1 && ['d'] ||
days < thresholds.d && ['dd', days] ||
months === 1 && ['M'] ||
months < thresholds.M && ['MM', months] ||
years === 1 && ['y'] || ['yy', years];
a[2] = withoutSuffix;
a[3] = +posNegDuration > 0;
a[4] = locale;
return substituteTimeAgo.apply(null, a);
}
function duration_humanize__getSetRelativeTimeThreshold (threshold, limit) {
if (thresholds[threshold] === undefined) {
return false;
}
if (limit === undefined) {
return thresholds[threshold];
}
thresholds[threshold] = limit;
return true;
}
function humanize (withSuffix) {
var locale = this.localeData();
var output = duration_humanize__relativeTime(this, !withSuffix, locale);
if (withSuffix) {
output = locale.pastFuture(+this, output);
}
return locale.postformat(output);
}
var iso_string__abs = Math.abs;
function iso_string__toISOString() {
var seconds = iso_string__abs(this._milliseconds) / 1000;
var days = iso_string__abs(this._days);
var months = iso_string__abs(this._months);
var minutes, hours, years;
minutes = absFloor(seconds / 60);
hours = absFloor(minutes / 60);
seconds %= 60;
minutes %= 60;
years = absFloor(months / 12);
months %= 12;
var Y = years;
var M = months;
var D = days;
var h = hours;
var m = minutes;
var s = seconds;
var total = this.asSeconds();
if (!total) {
return 'P0D';
}
return (total < 0 ? '-' : '') +
'P' +
(Y ? Y + 'Y' : '') +
(M ? M + 'M' : '') +
(D ? D + 'D' : '') +
((h || m || s) ? 'T' : '') +
(h ? h + 'H' : '') +
(m ? m + 'M' : '') +
(s ? s + 'S' : '');
}
var duration_prototype__proto = Duration.prototype;
duration_prototype__proto.abs = duration_abs__abs;
duration_prototype__proto.add = duration_add_subtract__add;
duration_prototype__proto.subtract = duration_add_subtract__subtract;
duration_prototype__proto.as = as;
duration_prototype__proto.asMilliseconds = asMilliseconds;
duration_prototype__proto.asSeconds = asSeconds;
duration_prototype__proto.asMinutes = asMinutes;
duration_prototype__proto.asHours = asHours;
duration_prototype__proto.asDays = asDays;
duration_prototype__proto.asWeeks = asWeeks;
duration_prototype__proto.asMonths = asMonths;
duration_prototype__proto.asYears = asYears;
duration_prototype__proto.valueOf = duration_as__valueOf;
duration_prototype__proto._bubble = bubble;
duration_prototype__proto.get = duration_get__get;
duration_prototype__proto.milliseconds = milliseconds;
duration_prototype__proto.seconds = seconds;
duration_prototype__proto.minutes = minutes;
duration_prototype__proto.hours = hours;
duration_prototype__proto.days = days;
duration_prototype__proto.weeks = weeks;
duration_prototype__proto.months = months;
duration_prototype__proto.years = years;
duration_prototype__proto.humanize = humanize;
duration_prototype__proto.toISOString = iso_string__toISOString;
duration_prototype__proto.toString = iso_string__toISOString;
duration_prototype__proto.toJSON = iso_string__toISOString;
duration_prototype__proto.locale = locale;
duration_prototype__proto.localeData = localeData;
duration_prototype__proto.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', iso_string__toISOString);
duration_prototype__proto.lang = lang;
addFormatToken('X', 0, 0, 'unix');
addFormatToken('x', 0, 0, 'valueOf');
addRegexToken('x', matchSigned);
addRegexToken('X', matchTimestamp);
addParseToken('X', function (input, array, config) {
config._d = new Date(parseFloat(input, 10) * 1000);
});
addParseToken('x', function (input, array, config) {
config._d = new Date(toInt(input));
});
utils_hooks__hooks.version = '2.10.6';
setHookCallback(local__createLocal);
utils_hooks__hooks.fn = momentPrototype;
utils_hooks__hooks.min = min;
utils_hooks__hooks.max = max;
utils_hooks__hooks.utc = create_utc__createUTC;
utils_hooks__hooks.unix = moment__createUnix;
utils_hooks__hooks.months = lists__listMonths;
utils_hooks__hooks.isDate = isDate;
utils_hooks__hooks.locale = locale_locales__getSetGlobalLocale;
utils_hooks__hooks.invalid = valid__createInvalid;
utils_hooks__hooks.duration = create__createDuration;
utils_hooks__hooks.isMoment = isMoment;
utils_hooks__hooks.weekdays = lists__listWeekdays;
utils_hooks__hooks.parseZone = moment__createInZone;
utils_hooks__hooks.localeData = locale_locales__getLocale;
utils_hooks__hooks.isDuration = isDuration;
utils_hooks__hooks.monthsShort = lists__listMonthsShort;
utils_hooks__hooks.weekdaysMin = lists__listWeekdaysMin;
utils_hooks__hooks.defineLocale = defineLocale;
utils_hooks__hooks.weekdaysShort = lists__listWeekdaysShort;
utils_hooks__hooks.normalizeUnits = normalizeUnits;
utils_hooks__hooks.relativeTimeThreshold = duration_humanize__getSetRelativeTimeThreshold;
var _moment = utils_hooks__hooks;
return _moment;
}));/**
* Google map popup plugin
*/
var googleMapPopUp = new function() {
var gMapPopUp = this;
this.init = function( settings ) {
gMapPopUp.locationData = settings.locationData;
gMapPopUp.mapsDisplayDomain = settings.mapsDisplayDomain;
gMapPopUp.longFreeCustomer = settings.longFreeCustomer;
gMapPopUp.language = settings.language;
var location = gMapPopUp.locationData.data('location');
gMapPopUp.locationData.on('click',function() {
buildPopup('popupRestaurantReservations','','',gMapPopUp.mapsDisplayDomain + '/include/globalMapDisplay.php?cad=1&q='+encodeURIComponent(location)+'&fl=1&l='+encodeURIComponent(gMapPopUp.language)+'&ilfc='+encodeURIComponent(gMapPopUp.longFreeCustomer),true,false,true,'','');
});
};
};jQuery(function($) {
DonateModuleInitialize_Layout1();
});
/**
* The function initialize the Donate Module.
*/
function DonateModuleInitialize_Layout1() {
$( document ).on( 's123.page.ready', function( event ) {
var $section = $('.s123-module.s123-module-donate.layout-1');
$section.each(function( index ) {
var $sectionThis = $(this);
var $donateForm = $sectionThis.find('.donateForm');
var $donateButton = $sectionThis.find('.updateCustom');
var $donateAmount = $sectionThis.find('.donate-amount');
$donateButton.off('click').on('click',function() {
$donateAmount.val($.trim($(this).data('amount')));
});
/**
* jQuery Validation Plugin Initial
* Documentation : http://jqueryvalidation.org/documentation/
*/
$donateForm.validate({
errorElement: 'div',
errorClass: 'help-block',
focusInvalid: true,
ignore: "",
highlight: function (e) {
$(e).closest('.form-group').removeClass('has-info').addClass('has-error');
},
success: function (e) {
$(e).closest('.form-group').removeClass('has-error');
$(e).remove();
},
errorPlacement: function (error, element) {
if( element.is('input[type=checkbox]') || element.is('input[type=radio]') ) {
var controls = element.closest('div[class*="col-"]');
if( controls.find(':checkbox,:radio').length > 1 ) controls.append(error);
else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
}
else if( element.is('.select2') ) {
error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
}
else if( element.is('.chosen-select') ) {
error.insertAfter(element.siblings('[class*="chosen-container"]:eq(0)'));
}
else {
error.appendTo(element.closest('.form-group'));
}
},
submitHandler: function( form ) {
var $form = $(form);
var formValues = getFormValues($form);
$('')
.appendTo('body')
.submit();
return false;
}
});
});
});
}jQuery(function($) {
foodDeliveryInitialize();
});
/**
* The function initialize the Menu Module.
*/
function foodDeliveryInitialize() {
$( document ).on( 's123.page.ready', function( event ) {
var $section = $('.s123-module-foodDelivery.layout-1');
$.each($section,function( index, section ) {
var $thisSection = $(section);
/**
* Categories initiilize
*/
(function() {
var $categories = $thisSection.find('.food-delivery-categories-container li');
var $products = $thisSection.find('.food-delivery-items-container > div');
$categories.off('click').on('click',function ( event, initialize ) {
var $category = $(this);
$categories.removeClass('active');
$category.addClass('active');
var $filtered = $products.filter('[data-product-filter=' + $category.data('categories-filter') + ']');
if ( initialize ) {
$products.hide();
$filtered.show();
} else {
$products.fadeOut(200).promise().done( function() {
$filtered.fadeIn(200);
$(window).trigger('scroll');
});
}
return false;
});
$categories.first().trigger('click',true);
$thisSection.find('.items-responsive-filter').click(function() {
var $category = $(this);
$thisSection.find('.categories-panel').slideToggle('slow');
$category.toggleClass('active');
return false;
});
})();
buisnessHoursTemplate.init({
$buisnessHourContainer : $thisSection.find('.foodDeliveryWorkingDaysTemplate'),
buisnessHourJSON : $thisSection.find(".foodDeliveryWorkingDays")
});
var buisnessIsActive = foodDeliveryCheckIfActive($thisSection.find(".foodDeliveryWorkingDays").val());
$thisSection.find('.popup-order-window').addClass('disabled');
if ( !buisnessIsActive ) {
$thisSection.find('.open-at').addClass('hidden');
return false;
} else {
$thisSection.find('.note-for-users').addClass('hidden');
$thisSection.find('.early-orders').addClass('hidden');
}
$thisSection.find('.popup-order-window').removeClass('disabled');
var additionalData = {
productEdit: false
};
$.each($thisSection.find('.popup-order-window'),function( index, item ) {
foodDeliveryProductPopUpEvent($(item),additionalData,true);
});
$.each($thisSection.find('.item-image.online-orders-active'),function( index, item ) {
foodDeliveryProductPopUpEvent($(item),additionalData,true);
});
});
});
}
/**
* The function is adding to the item onclick event that will show the popup window.
*
* @param {object} object - HTML element that will receive the event.
* @param {String} String - Cart iframe src.
* @param {object} object - HTML element - identification if we should show the cart popup (mobile only).
* @param {boolean} boolean - true / false - identification if we should trigger the popup event.
*/
function foodDeliveryProductPopUpEvent( $addToOrder, additionalData, buildPopUp ) {
$addToOrder.off('click').on('click',function() {
var $itemParent = $(this).parents('.food-delivery-item-parent');
var itemData = {};
itemData.options = tryParseJSON($itemParent.find('.productOptionsSettings').val());
itemData.customText = tryParseJSON($itemParent.find('.customTextSettings').val());
itemData.addToCartData = tryParseJSON($itemParent.find('.hidden-add-to-cart').val());
var itemHTML = foodDeliveryGenerateItemHTML(itemData,$itemParent);
/**
* Build the item window, documentation:
* http://bootboxjs.com/documentation.html
*/
var $foodDeliveryWindow = bootbox.dialog({
title: translations.foodDeliverybootBoxTitle,
message: itemHTML,
className: 'foodDeliveryItemWindow',
backdrop: true,
onEscape: function() {},
callback: function () {}
});
/* when the user is editing a product from the cart popup we need to open the food delivery item poup on the cart popup
so we set the food delivery poup z-index higher by 1 then the cart poup */
if ( $('#popupCart').length > 0 ) $foodDeliveryWindow.css('zIndex',parseInt($('#popupCart').css('zIndex'))+1);
$foodDeliveryWindow.on('shown.bs.modal', function() {
$popUpWindow = $(this);
$popUpWindow.find('.btn-buy-now').off('click').on('click',function() {
var $this = $(this);
if ( !ActiveOrderPopup.atcValidator() ) return;
$foodDeliveryWindow.data('added-to-cart',true);
$this.attr('disabled','');
$.ajax({
type: "POST",
url: "/versions/"+$('#versionNUM').val()+"/wizard/orders/front/addToCart.php",
data: {
w: $('#w').val(),
websiteID: $('#websiteID').val(),
uniquePageID: $this.data('unique-page'),
moduleID: $this.data('module'),
moduleTypeNUM : '97',
productOptions: $popUpWindow.find('#productOptions').length !== 0 ? $popUpWindow.find('#productOptions').val() : '',
customText: $popUpWindow.find('#customText').length !== 0 ? $popUpWindow.find('#customText').val() : '',
productEdit: additionalData.productEdit
},
success: function() {
$foodDeliveryWindow.modal('hide');
$this.removeAttr('disabled');
}
});
});
if ( additionalData.productEdit ) {
$popUpWindow.find('.btn-buy-now').html(translations.save);
foodDeliveryOptionsInit($addToOrder);
foodDeliveryOptionsLoad($popUpWindow,additionalData.productOptions);
foodDeliveryCustomTextInit($popUpWindow);
if ( additionalData.customText.length > 0 ) $popUpWindow.find('#ct_fieldTitle').val(additionalData.customText).trigger('input');
} else {
foodDeliveryOptionsInit($addToOrder);
foodDeliveryOptionsLoad($popUpWindow,additionalData.productOptions);
foodDeliveryCustomTextInit($popUpWindow);
}
});
$foodDeliveryWindow.on('hide.bs.modal', function() {
$('.product-validator-popover').popover('hide');
var moduleID = $foodDeliveryWindow.find('.btn-buy-now').data('module');
if ( $foodDeliveryWindow.data('added-to-cart') ) showCart_GetContent('/versions/'+$('#versionNUM').val()+'/wizard/orders/front/showCart.php?w='+$('#w').val()+'&websiteID='+$('#websiteID').val()+'&moduleID='+moduleID+'&moduleTypeNUM=97&tranW='+websiteLanguageCountryFullCode,buildPopUp);
});
});
if ( additionalData.productEdit ) $addToOrder.trigger('click');
}
/**
* The function is loading the product options to the popup window when clicking
* on the product edit on the product name.
*
* @param {Object} - Modal dialog window
* @param {Object} - Product options JSON
*/
function foodDeliveryOptionsLoad( popUpWindow, productOptions ) {
if( !productOptions ) {
popUpWindow.find('.p-o-radio-button').find('[name="foodDeliverRadion"]').first().trigger('click');
} else {
$.each(productOptions.options,function( index, option ) {
popUpWindow.find('#'+option.item.id).trigger('click');
});
}
}
/**
* The function is checking if the business is active today
* and if it is the order now button is enabled else it's disabled.
*
* @param {Object} - Product options JSON
* @return {boolean} -
*/
function foodDeliveryCheckIfActive( buisnessHours ) {
if ( !tryParseJSON(buisnessHours) ) return false;
var object = tryParseJSON(buisnessHours);
var earlyOrders = object.earlyOrders;
var fullTime = object.fullTime;
var hours = object.businessHours;
var firstDayOfWeek = object.firstDayOfWeek;
if (firstDayOfWeek == '' || hours=='[]' || firstDayOfWeek == '') {
return false;
}
var dayOfTheWeek = moment(object.today).day();
if ( dayOfTheWeek == 0) {
if ( parseInt(firstDayOfWeek) == 1 ) {
var dataIndex = 6;
} else {
var dataIndex = dayOfTheWeek;
}
} else {
var dataIndex = dayOfTheWeek - parseInt(firstDayOfWeek);
}
if (hours[dataIndex].isActive || fullTime == 'on' || earlyOrders == 'yes') {
return true;
} else {
return false;
}
}
/**
* Product option initilize
*/
function foodDeliveryOptionsInit( $thisSection ) {
var $foodDeliveryItemWindow = $('.foodDeliveryItemWindow');
var $productOptions = $foodDeliveryItemWindow.find(".product-options");
var $options = $productOptions.find('.p-o-container');
$.each($('.bootbox-item-price').find('span'), function( index, span ) {
if ($(span).data('type') == 'price') {
$(span).data('price',$(span).html());
}
});
if ( $productOptions.length !== 0 ) {
$options.filter('[data-type="checkbox"]').each( function() {
var $option = $(this);
var $checkbox = $option.find('.p-o-check-box').find('input[type="checkbox"]');
$checkbox.click( function( event ) {
$checkbox.filter('.selected').removeClass('selected');
foodDeliveryItemOptionsUpdate($thisSection);
});
});
$options.filter('[data-type="radio"]').each( function() {
var $option = $(this);
var $radio = $option.find('.p-o-radio-button').find('input[type="radio"]');
$radio.click( function( event ) {
$radio.filter('.selected').removeClass('selected');
foodDeliveryItemOptionsUpdate($thisSection);
});
});
}
}
/**
* The function update the product options object.
*/
function foodDeliveryItemOptionsUpdate( $thisSection ) {
var po = [];
var totalItemsPrice = 0.00;
var $options = $('.foodDeliveryItemWindow .product-options .p-o-container');
$options.each( function() {
var $option = $(this);
switch( $option.data('type') ) {
case 'checkbox':
var $checkbox = $option.find('.p-o-check-box').find('input[type="checkbox"]:checked');
var $checkboxUnchecked = $option.find('.p-o-check-box').find('input[type="checkbox"]:unchecked');
$.each($checkbox,function( index, checkbox ) {
var pOption = new foodDeliveryProductOptions();
pOption.id = $option.get(0).id;
pOption.title = foodDeliveryFixQuotIssue($option.data('title'));
pOption.type = $option.data('type');
pOption.item.id = $(checkbox).get(0).id;
pOption.item.title = foodDeliveryFixQuotIssue($(checkbox).val());
pOption.item.price = $(checkbox).data('price');
totalItemsPrice += parseFloat(pOption.item.price);
po.push(pOption);
foodDeliveryChangePrice(po);
});
$.each($checkboxUnchecked,function( index, checkbox ) {
foodDeliveryChangePrice(po);
});
break;
case 'radio':
var pOption = new foodDeliveryProductOptions();
pOption.id = $option.get(0).id;
pOption.title = foodDeliveryFixQuotIssue($option.data('title'));
pOption.type = $option.data('type');
var $radio = $option.find('.p-o-radio-button').find('input[type="radio"]:checked');
pOption.item.id = $radio.get(0).id;
pOption.item.title = foodDeliveryFixQuotIssue($radio.val());
pOption.item.price = $radio.data('price');
totalItemsPrice += parseFloat(pOption.item.price);
po.push(pOption);
foodDeliveryChangePrice(po);
break;
}
});
$('.foodDeliveryItemWindow #productOptions').val(JSON.stringify(po));
foodDeliveryAddItemsPrice(totalItemsPrice,$thisSection);
}
/**
* Change the price in the span element.
*/
function foodDeliveryChangePrice( po ) {
var $priceSpan = $('.bootbox-item-price.total').find('span[data-type="price"]');
var price = parseFloat($priceSpan.data('price'));
$.each(po,function( index, value ) {
price = parseFloat(value.item.price) + price;
});
$priceSpan.html(price);
}
/**
* Product Option Class.
*/
function foodDeliveryProductOptions() {
return {
id: null,
title: null,
type: null,
item: {
id: null,
title: null,
price: 0
}
};
}
/**
* The function add product items price to the product price.
* @param {float} totalItemsPrice - The total items price.
*/
function foodDeliveryAddItemsPrice( totalItemsPrice, $thisSection ) {
var $productPrice = $thisSection.find('#productPrice');
var $price = $productPrice.find('[data-type="price"]');
if ( !$.isNumeric(totalItemsPrice) ) return;
if ( parseFloat($productPrice.data('price'))
+ parseFloat(totalItemsPrice) == parseFloat($price.html()) ) return;
var p = parseFloat($productPrice.data('price')) + parseFloat(totalItemsPrice);
$price.html(p.toFixed(2));
}
/**
* Product Custom Text
*/
function foodDeliveryCustomTextInit( $popUpWindow ) {
var $ct = $('.foodDeliveryItemWindow').find('#product-custom-text');
var $ct_fieldTitle = $ct.find("#ct_fieldTitle");
var $ct_charLimit = $ct.find("#ct_charLimit");
var $orderButtonPopup = $popUpWindow.find(".btn-buy-now");
$ct_fieldTitle.on('input', function( event ) {
var max = $ct.data('char-limit');
var length = $ct_fieldTitle.val().length
if ( length > max) {
$ct_fieldTitle.val($ct_fieldTitle.val().substring(0, max));
} else {
$ct_charLimit.html(max - length);
}
$popUpWindow.find('#customText').empty();
foodDeliveryCustomTextUpdate($popUpWindow,$ct,$ct_fieldTitle);
});
}
/**
* The function update the custom text object.
*/
function foodDeliveryCustomTextUpdate( $popUpWindow, $ct, $ct_fieldTitle ) {
if ( $ct_fieldTitle.val().length === 0 ) return;
var ct = new foodDeliveryCustomText();
ct.fieldTitle = foodDeliveryFixQuotIssue($ct.data('field-title'));
ct.value = $ct_fieldTitle.val();
$popUpWindow.find('#customText').html(JSON.stringify(ct));
}
/**
* Custom Text Class.
*/
function foodDeliveryCustomText() {
return {
fieldTitle: null,
value: null
};
}
/**
* The function convert `"` to `"`, We use data attribute to to pass
* some of the fields with `htmlspecialchars()` on the server side to
* prevent HTML break with quot, the JS function `stringify` doesn't
* handle `"` chars so we fix it manually by replacing it to `"`.
* In the feature we need to stop passing the values using `data`.
*/
function foodDeliveryFixQuotIssue( value ) {
if ( !value ) return value;
return value.toString().replace(/\"/g,'\"');
}
/**
* Generate the HTML string of the the item box.
* @param {Object} -> Item Data.
*/
function foodDeliveryGenerateItemHTML( itemData, $itemParent ) {
var html ='';
html += foodDeliveryBootBoxTemplate();
var imageSrc = $itemParent.find('.item-image').css('background-image');
if(imageSrc) {
imageSrc = imageSrc.replace('url(','').replace(')','').replace(/\"/gi, "");
} else {
imageSrc =' ';
}
html = html.replace('{{imgsrc}}',imageSrc);
var itemPrice = '';
if ($itemParent.find('.item-details > .item-price').length > 0 ) {
var itemPrice = $itemParent.find('.item-details > .item-price').html();
}
html = html.replace('{{Price}}',itemPrice);
html = html.replace('{{Total}}',itemPrice);
var itemTitle = $itemParent.find('.item-details > h4').html();
html = html.replace('{{Header}}',itemTitle);
var itemDescription = $itemParent.find('.item-details > .item-des').html();
html = html.replace('{{Des}}',itemDescription);
var optionsHTML = foodDeliveryGenerateItemOptionsHTML(itemData.options);
html = html.replace('{{itemOptions}}',optionsHTML);
var customTextHTML = foodDeliveryGenerateCustomText(itemData.customText);
html = html.replace('{{customText}}',customTextHTML);
var addToCart = foodDeliveryGenerateAddToCartBtn(itemData.addToCartData);
html = html.replace('{{addToCart}}',addToCart);
return html;
}
/**
* Generate the HTML string of the Custom text.
* @param {Object} -> Custom Text Structure.
*/
function foodDeliveryGenerateCustomText( customTextData ) {
var html ='';
if ( customTextData.active ) {
html = '
';
html += '
';
html += '';
html += '
';
html += '';
html += ''+customTextData.charLimit+'';
html += '
';
html += '
';
html += '';
html += '
';
}
return html;
}
/**
* Generate the HTML string of add to cart button.
* @param {Object} -> module id and item unique id.
*/
function foodDeliveryGenerateAddToCartBtn( addToCartData ) {
var html = '';
html += ''+translations.addToCart+'';
return html;
}
/**
* Generate the HTML string of the product option.
* @param {Object} product option structure.
*/
function foodDeliveryGenerateItemOptionsHTML( optionsJSON ) {
var html ='';
var websiteCurrency = $('[data-type="symbol"]').html();
if ( optionsJSON.active ) {
html = '
';
switch ( option.type ) {
case 'color':
html += '
';
$.each( option.items,function( index, item ) {
if ( !item.price ) item.price = 0;
html += '
';
});
html += '
';
break;
case 'checkbox':
html += '
';
$.each( option.items,function( index, item ) {
if ( !item.price ) item.price = 0;
html += '';
});
html += '
';
break;
case 'radio':
html += '
';
$.each( option.items,function( index, item ) {
if ( !item.price ) item.price = 0;
html += '';
});
html += '
';
break;
}
html += '
';
});
});
html += '';
html += '
';
}
return html;
}
/**
* The function convert special characters to HTML entities, we use it when
* we add strings into HTML attributes, it used to prevent the breaks in
* the HTML e.g. title="abc"efg".
*
* Source: http://stackoverflow.com/questions/1787322/htmlspecialchars-equivalent-in-javascript
*/
function foodDeliveryEscapeHtml( text ) {
if ( !text ) return text;
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.toString().replace( /[&<>"']/g, function( m ) { return map[m]; } );
}
/**
* The function is adding to the cart popup food delivery type edit product ability.
*
* @param {jq object} $cartOrderPage - Cart popup with the elemtnts.
*/
function foodDeliveryEditProductEvent( $cartOrderPage ) {
$cartOrderPage.find('.edit-product, .product-name').off('click').on('click',function() {
var $thisSection = $('.s123-module-foodDelivery.layout-1');
var productID = $(this).data('productid');
var uniquepageID = $(this).data('uniquepageid');
var cartType = $(this).data('carttype');
var customText = $(this).data('customtext');
var productOptions = tryParseJSON($(this).closest('.row.item').find('.hidden-product-options').val());
$.each($thisSection.find('.hidden-add-to-cart'),function( index, data ) {
var productData = tryParseJSON($(data).val());
/* if the data is the same that means we need
to trigger the popup window for this specific item */
if ( productData.uniqueID == uniquepageID ) {
var $addToOrder = $(this).closest('.food-delivery-item-parent').find('.popup-order-window');
var additionalData = {};
additionalData.productEdit = true;
additionalData.productOptions = productOptions;
additionalData.customText = customText;
foodDeliveryProductPopUpEvent($addToOrder,additionalData,false);
}
});
});
}function foodDeliveryBootBoxTemplate() {
var html = '';
html += '
';
html += '
';
html += '';
html += '
';
html += '
';
html += '{{Header}}';
html += '
{{Price}}
';
html += '
{{Des}}
';
html += '
';
html += '
';
html += '{{itemOptions}}';
html += '
';
html += '
';
html += '{{customText}}';
html += '
';
html += '
';
html += '
';
html += translations.total + ' {{Total}}';
html += '
';
html += '
';
html += '
';
html += '{{addToCart}}';
html += '
';
html += '
';
return html;
}jQuery(function($) {
PortfolioModuleInitialize_Layout1();
});
/**
* The function initialize the Portfolio Module.
*/
function PortfolioModuleInitialize_Layout1() {
$( document ).on( 's123.page.ready', function( event ) {
var $section = $('section.s123-module-portfolio.layout-1');
$section.each(function( index ) {
var $sectionThis = $(this);
var $categories = $sectionThis.find('.filter li');
var $images = $sectionThis.find('.portfolio-image');
$categories.off('click').on('click',function ( event, initialize ) {
var $category = $(this);
$categories.removeClass('active');
$category.addClass('active');
$sectionThis.css({ minHeight: $sectionThis.height() });
var $filtered = $category.data('filter') == 's123-g-show-all' ? $images : $images.filter('[data-filter=' + $category.data('filter') + ']');
if ( initialize ) {
$images.hide();
$filtered.show();
} else {
$images.fadeOut(200).promise().done( function() {
$filtered.fadeIn(200);
$sectionThis.css({ minHeight: '' });
$(window).trigger('scroll');
});
}
return false;
});
$categories.first().trigger('click',true);
});
});
}jQuery(function($) {
AgendaModuleInitialize();
});
/**
* The function initialize the Agenda Module.
*/
function AgendaModuleInitialize() {
$( document ).on( "s123.page.ready", function( event ) {
var $sections = $('.s123-module-agenda.layout-2');
$sections.each(function( index ) {
var $s = $(this);
var $categories = $s.find('.filter a');
$categories.off('click').on('click',function ( event, initialize ) {
var $category = $(this);
var $agenda = $s.find('.agenda-category');
$s.find('.filter li').removeClass('active');
$category.parent().addClass('active');
var $filtered = $agenda.filter('[data-filter=' + $category.data('filter') + ']');
if ( initialize ) {
$agenda.hide();
$filtered.show();
} else {
$agenda.fadeOut(200).promise().done( function() {
$filtered.fadeIn(200);
$(window).trigger('scroll');
});
}
return false;
});
$categories.first().trigger('click',true);
});
});
}jQuery(function($) {
AgendaModuleInitialize_Layout3();
});
/**
* The function initialize the Agenda Module.
*/
function AgendaModuleInitialize_Layout3() {
$( document ).on( "s123.page.ready", function( event ) {
var $sections = $('.s123-module-agenda.layout-3');
$sections.each(function( index ) {
var $s = $(this);
var $categories = $s.find('.agenda-categories-container li');
var $agenda = $s.find('.agenda-category');
$categories.off('click').on('click',function ( event, initialize ) {
var $category = $(this);
$categories.removeClass('active');
$category.addClass('active');
var $filtered = $agenda.filter('[data-filter=' + $category.data('filter') + ']');
if ( initialize ) {
$agenda.hide();
$filtered.show();
} else {
$agenda.fadeOut(200).promise().done( function() {
$filtered.fadeIn(200);
$(window).trigger('scroll');
});
}
return false;
});
$categories.first().trigger('click',true);
$s.find('.agenda-responsive-filter').off('click').on('click', function() {
var $category = $(this);
$s.find('.categories-panel').slideToggle('slow');
$category.toggleClass('active');
return false;
});
});
});
}/*
* International Telephone Input v8.5.2
* https://github.com/jackocnr/intl-tel-input.git
* Licensed under the MIT license
*/
(function(factory) {
if (typeof define === "function" && define.amd) {
define([ "jquery" ], function($) {
factory($, window, document);
});
} else if (typeof module === "object" && module.exports) {
module.exports = factory(require("jquery"), window, document);
} else {
factory(jQuery, window, document);
}
})(function($, window, document, undefined) {
"use strict";
var pluginName = "intlTelInput", id = 1, // give each instance it's own id for namespaced event handling
defaults = {
allowDropdown: true,
autoHideDialCode: true,
autoPlaceholder: true,
customPlaceholder: null,
dropdownContainer: "",
excludeCountries: [],
formatOnInit: true,
geoIpLookup: null,
initialCountry: "",
nationalMode: true,
numberType: "MOBILE",
onlyCountries: [],
preferredCountries: [ "us", "gb" ],
separateDialCode: false,
utilsScript: ""
}, keys = {
UP: 38,
DOWN: 40,
ENTER: 13,
ESC: 27,
PLUS: 43,
A: 65,
Z: 90,
SPACE: 32,
TAB: 9
};
$(window).load(function() {
$.fn[pluginName].windowLoaded = true;
});
function Plugin(element, options) {
this.telInput = $(element);
this.options = $.extend({}, defaults, options);
this.ns = "." + pluginName + id++;
this.isGoodBrowser = Boolean(element.setSelectionRange);
this.hadInitialPlaceholder = Boolean($(element).attr("placeholder"));
}
Plugin.prototype = {
_init: function() {
if (this.options.nationalMode) {
this.options.autoHideDialCode = false;
}
if (this.options.separateDialCode) {
this.options.autoHideDialCode = this.options.nationalMode = false;
this.options.allowDropdown = true;
}
this.isMobile = /Android.+Mobile|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
if (this.isMobile) {
$("body").addClass("iti-mobile");
if (!this.options.dropdownContainer) {
this.options.dropdownContainer = "body";
}
}
this.autoCountryDeferred = new $.Deferred();
this.utilsScriptDeferred = new $.Deferred();
this._processCountryData();
this._generateMarkup();
this._setInitialState();
this._initListeners();
this._initRequests();
return [ this.autoCountryDeferred, this.utilsScriptDeferred ];
},
/********************
* PRIVATE METHODS
********************/
_processCountryData: function() {
this._processAllCountries();
this._processCountryCodes();
this._processPreferredCountries();
},
_addCountryCode: function(iso2, dialCode, priority) {
if (!(dialCode in this.countryCodes)) {
this.countryCodes[dialCode] = [];
}
var index = priority || 0;
this.countryCodes[dialCode][index] = iso2;
},
_filterCountries: function(countryArray, processFunc) {
var i;
for (i = 0; i < countryArray.length; i++) {
countryArray[i] = countryArray[i].toLowerCase();
}
this.countries = [];
for (i = 0; i < allCountries.length; i++) {
if (processFunc($.inArray(allCountries[i].iso2, countryArray))) {
this.countries.push(allCountries[i]);
}
}
},
_processAllCountries: function() {
if (this.options.onlyCountries.length) {
this._filterCountries(this.options.onlyCountries, function(inArray) {
return inArray != -1;
});
} else if (this.options.excludeCountries.length) {
this._filterCountries(this.options.excludeCountries, function(inArray) {
return inArray == -1;
});
} else {
this.countries = allCountries;
}
},
_processCountryCodes: function() {
this.countryCodes = {};
for (var i = 0; i < this.countries.length; i++) {
var c = this.countries[i];
this._addCountryCode(c.iso2, c.dialCode, c.priority);
if (c.areaCodes) {
for (var j = 0; j < c.areaCodes.length; j++) {
this._addCountryCode(c.iso2, c.dialCode + c.areaCodes[j]);
}
}
}
},
_processPreferredCountries: function() {
this.preferredCountries = [];
for (var i = 0; i < this.options.preferredCountries.length; i++) {
var countryCode = this.options.preferredCountries[i].toLowerCase(), countryData = this._getCountryData(countryCode, false, true);
if (countryData) {
this.preferredCountries.push(countryData);
}
}
},
_generateMarkup: function() {
this.telInput.attr("autocomplete", "off");
var parentClass = "intl-tel-input";
if (this.options.allowDropdown) {
parentClass += " allow-dropdown";
}
if (this.options.separateDialCode) {
parentClass += " separate-dial-code";
}
this.telInput.wrap($("
';
html += ''+translations.joined+' ';
html += ''+translations.posted+' ';
html += ''+translations.forumCountOfTotalPosts.replace('{{numbers_of_posts}}','')+'';
'+translations.countOfTotalPosts+'
html += '
';
html += '
';
var $html = $(html);
var avatar = Forum_setAvatar(data.profileImage,400,data.nickname,data.avatarColor);
var $avatar = $(avatar);
$html.find('.forum-card-avatar').append($avatar);
$html.find('.forum-card-avatar span').addClass('avatar-img');
if ( data.nickname.length > 1 ) {
$html.find('.client-card-name span').html(data.nickname);
}
$html.find('.client-card-join').html(data.joined);
if ( data.lastPost.length > 0 ) {
$html.find('.client-card-last-post').html(data.lastPost).show();
}
if ( data.totalPosts > 0 ) {
$html.find('.client-card-total-posts').html(data.totalPosts).show();
}
if (callback) callback.call(this,$html,$button);
}
/**
* Initialize popover
*/
function Forum_initializePopover( html, $button ) {
var $html = $(html);
$button.popover({
container: 'body',
html: 'true',
content: $html,
trigger: 'manual',
template: '
',
placement: function(popover, button) {
if ( isMobile.any() ) return 'auto';
if ( $(button).hasClass('side-menu-popover') ) {
return $('html[dir=rtl]').length === 1 ? 'right' : 'left';
}
return $('html[dir=rtl]').length === 1 ? 'left' : 'right';
}
});
$button.popover('show');
$button.on('shown.bs.popover', function () {
$(document).on('mousedown.forumDestroyPopover', function ( event ) {
if ( $(event.target).closest('.popover.share-reply').length === 0 ) {
destroyClientCardPopover();
}
});
});
/**
* The function destroy the Popover and removes event handlers that were attached to it
*/
function destroyClientCardPopover() {
$button.popover('destroy');
$(document).off('mousedown.forumDestroyPopover');
$(window).off('blur.forumDestroyPopover');
$(window).off('scroll.forumDestroyPopover');
}
}
/**
* Initialize client card
*/
function Forum_initializeClientCard( $button, websiteID, w, itemUniqueID ) {
$button.click(function() {
var clientID = $(this).data('client-id');
Forum_getClientDetails(w,websiteID,clientID,itemUniqueID,$button,Forum_generateClientCard);
});
}
/**
* Initialize search
*/
function Forum_initializeSearch( $section, websiteID, itemUniqueID, searchURL, dateTime ) {
var direction = $('html[dir=rtl]').length === 1 ? 'left' : 'right';
var html = '
';
html += '';
html += '
';
html += '';
html += '
';
html += '';
html += '
';
var $html = $(html);
var $form = $html.find('form');
var $resultsContainer = $html.find('.forum-results-container');
var $loading = $html.find('.forum-search-loading');
var $search = $form.find('.forum-search-input');
$form.submit(function(e) {
e.preventDefault();
});
$search.on('keydown', function(event) {
var eventKey = event.which;
clearTimeout($search.inputFinished);
$search.inputFinished = setTimeout( function() {
if ( !$search.val() ) {
$resultsContainer.slideUp(200).html('');
return;
}
$resultsContainer.slideUp(200).html('');
$loading.fadeIn();
Forum_search($form,$resultsContainer,$loading,searchURL,dateTime,Forum_generateSearchResult);
$form.find('.forum-search-option').attr('href',searchURL+'&q='+$form.find('[name=q]').val());
},500);
});
$section.find('.forum-search-btn').each(function(key, button){
var $button = $(button);
if ( isMobile.any() ) {
$button.attr('href',searchURL+'&q=').removeAttr('onclick');
return false;
}
$button.off('click').on('click', function(){
var $button = $(this);
$(this).popover({
container: 'body',
html: 'true',
content: $html,
trigger: 'manual',
template: '
',
placement: function(popover, button) {
return 'bottom';
}
});
$button.popover('show');
$search.focus();
$button.on('shown.bs.popover', function () {
$(document).on('mousedown.forumDestroyPopover', function ( event ) {
if ( $(event.target).closest('.popover.forum-search').length === 0 ) {
destroySearchPopover();
}
});
});
/**
* The function destroy the Popover and removes event handlers that were attached to it
*/
function destroySearchPopover() {
$button.popover('destroy');
$(document).off('mousedown.forumDestroyPopover');
$(window).off('blur.forumDestroyPopover');
$(window).off('scroll.forumDestroyPopover');
}
});
});
}
/**
* Search
*/
function Forum_search( $form, $resultsContainer, $loading, searchURL, dateTime, callback ) {
$.ajax({
type: "POST",
url: "/versions/"+$('#versionNUM').val()+"/wizard/modules/forum/search.php",
data: $form.serialize(),
success: function( data ) {
var dataObj = jQuery.parseJSON(data);
if (callback) callback.call(this,dataObj,$resultsContainer,$loading,searchURL,dateTime);
}
});
}
/**
* Generate search result
*/
function Forum_generateSearchResult( resultsData, $resultsContainer, $loading, searchURL, dateTime ) {
if ( resultsData.status == 'fail' || resultsData.length === 0 ) {
var html = '
' + resultsData.msg + '
';
var $html = $(html);
$loading.fadeOut();
$resultsContainer.append($html).slideDown(200);
return;
}
dateTime = new Date(dateTime);
var index = 0;
var html = '
';
html += '
';
$.each(resultsData.results, function(key,data) {
if ( index > 4 ) return false;
index = index + 1;
var createTime = new Date(data.createTime);
var diff = dateTime - createTime;
html += '
';
}
var $html = $(html);
$resultsContainer.append($html);
if ( index >= resultsData.results.length ) {
$resultsContainer.find('ul.forum-results-list li:last-child').addClass('forum-last-result');
}
$loading.fadeOut();
$resultsContainer.slideDown(200);
return;
}
/**
* // initialize topics lazy load
*/
function Forum_getTopics( $container, websiteID, callback, itemUniqueID, hasCategories ) {
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
if ( $container.data('is-loading') == 'true' ) return false;
var html = '
';
$container.append($(html));
Forum_loadTopics($container,websiteID,callback,itemUniqueID,hasCategories);
}
});
}
/**
* Load topics
*/
function Forum_loadTopics( $container, websiteID, callback, itemUniqueID, hasCategories ) {
$container.data('is-loading','true');
$.ajax({
type: "POST",
url: "/versions/"+$('#versionNUM').val()+"/wizard/modules/forum/loadTopics.php",
data: {
w : $('#w').val(),
websiteID : websiteID,
itemUniqueID : itemUniqueID,
page : $container.data('page'),
categoryUniqueID : $container.data('category-id')
},
dataType: "json",
success: function( data ) {
$container.data('page',parseInt($container.data('page')) + 1);
if (callback) callback.call(this,data,$container,websiteID,itemUniqueID,hasCategories);
}
});
}
/**
* The function get forum data
*/
function Forum_getData( $container, $topics, w, websiteID, categoryUniqueID, hasCategories, callback ) {
$.ajax({
type: "POST",
url: "/versions/"+$('#versionNUM').val()+"/wizard/modules/forum/getForumData.php",
data: 'w='+w+'&websiteID='+websiteID+'&categoryUniqueID='+categoryUniqueID,
success: function( data ) {
var data = jQuery.parseJSON(data);
$container.data('date-time',data.dateTime);
if (callback) callback.call(this,data,$container,$topics,w,websiteID,categoryUniqueID,hasCategories);
}
});
}
function Forum_ActiveSoftLabelInputs() {
$('.newTopicForm .softLabel,#popupEditTopicReply .softLabel').each(function() {
var $this = $(this);
if ($this.find('input[type="text"],input[type="email"],input[type="number"]').val()!='' || typeof $this.find('input[type="text"],input[type="email"],input[type="number"]').attr('placeholder') !== 'undefined') {
$this.find('label').addClass('active');
}
});
$('.newTopicForm .softLabel > label, #popupEditTopicReply .softLabel > label').on('click',function() {
var $this = $(this);
$this.parents('.softLabel').find('input[type="text"],input[type="email"],input[type="number"]').trigger('focus');
});
$('.newTopicForm .softLabel > input[type="text"],input[type="email"],input[type="number"], #popupEditTopicReply .softLabel > input[type="text"],input[type="email"],input[type="number"]').on('focus',function() {
var $this = $(this);
$this.parents('.softLabel').find('label').addClass('active');
});
$('.newTopicForm .softLabel > input[type="text"],input[type="email"],input[type="number"], #popupEditTopicReply .softLabel > input[type="text"],input[type="email"],input[type="number"]').on('blur',function() {
var $this = $(this);
if ($this.val()=='' && typeof $this.attr('placeholder') === 'undefined') {
$this.parents('.softLabel').find('label').removeClass('active');
}
});
}jQuery(function($) {
ForumModuleInitialize_Topics();
});
/**
* The function initialize the Forum Module.
*/
function ForumModuleInitialize_Topics() {
$( document ).on( 's123.page.ready', function( event ) {
var w = $('#w').val();
var $section = $('section.s123-module-forum.forum-topics');
$section.each(function( index ) {
var $sectionThis = $(this);
var $forumContainer = $sectionThis.find('.forum-container');
var $infoBtn = $sectionThis.find('.forum-info-btn');
var websiteID = $forumContainer.data('website-id');
var itemUniqueID = $forumContainer.data('module-unique-id');
var categoryUniqueID = $forumContainer.data('category-id') ? $forumContainer.data('category-id') : '' ;
var searchURL = $forumContainer.data('search-url');
var hasCategories = !jQuery.isEmptyObject($forumContainer.data('categories'));
if ( $forumContainer.length > 0 ) {
Forum_getData($forumContainer,$forumContainer,w,websiteID,categoryUniqueID,hasCategories,initializeForumTopics);
}
Forum_initializeSearch($sectionThis,websiteID,itemUniqueID,searchURL,$forumContainer.data('date-time'));
/**
* We loading more topics with lazy load through AJAX escape from the following cases:
* 1. Categories page - the page that display the all categories (to display the all
* categories page we need to use URL querystring that include 'arrange=categories').
* 2. If on the first time the topics page was loaded with less then 12 topics (it's
* mean there was less then 12 topics so we don't need to load more topics)
*/
if( window.location.href.indexOf('arrange=categories') === -1 && $forumContainer.find('.topics-subject').length > 11 ) {
Forum_getTopics($forumContainer,websiteID,addMoreTopics,itemUniqueID,hasCategories);
}
$infoBtn.off('click').click(function(){
generateForumInfoPopUp(w,websiteID,categoryUniqueID);
});
});
});
}
/**
* The function add more topics results to the page
*/
function addMoreTopics( data, $container, websiteID, itemUniqueID, hasCategories ) {
if ( data.status == 'fail' || !data.topics || data.topics.length === 0 ) {
var html = '
';
var $html = $(html);
if ( data.msg ) {
$html.find('span b').html(data.msg);
}
$container.append($html);
$container.find('.forum-load-more-loading').remove();
} else {
var w = $('#w').val();
var moreTopics = '
' + data.topics + '
';
var $moreTopics = $(moreTopics);
$moreTopics.find('.forum-avatar').each(function(key,value){
Forum_initializeClientCard($(value),websiteID,w,itemUniqueID);
});
Forum_updateActivityDateTime($container.data('date-time'),$moreTopics.find('.topic-last-activity'));
Forum_getData($container,$moreTopics,w,websiteID,itemUniqueID,hasCategories,initializeMoreTopics);
}
}
/**
* The function initialize topics
*/
function initializeTopics( data, $container, $moreTopics, w, websiteID, itemUniqueID, hasCategories ) {
$moreTopics.find('.forum-topic').each(function(){
var $topic = $(this);
var $button = $topic.find('.topic-buttons-container');
var $topicTitle = $container.find('.topic-title');
if ( (data.loggedIn == 'true' || data.isManagment == true) && data.manager == 'true' ) {
var topicID = $button.data('topic-id');
var html = '
';
html += '';
html += '
';
$html = $(html);
initializeTopicsButtons(websiteID,topicID,itemUniqueID,$html);
$button.append($html).show();
$container.find('.manage-topic-title').show();
if ( hasCategories ) {
$topicTitle.attr('class', 'topic-title col-sm-2 col-md-3');
$container.find('.topics-users').attr('class', 'topics-users col-sm-1 col-md-2');;
$topic.find('.forum-category').attr('class', 'forum-category hidden-xs col-sm-2');
$topic.find('.topics-subject').attr('class', 'topics-subject col-xs-7 col-sm-2 col-md-3');
$topicsAvatar = $topic.find('.topics-avatar-row').each(function (index, value){
$value = $(value);
if ( $value.hasClass('visible-xs') ) {
$value.attr('class', 'topics-avatar-row visible-xs col-xs-2 col-sm-1 col-md-2');
}
if ( $value.hasClass('hidden-xs') ) {
$value.attr('class', 'topics-avatar-row hidden-xs col-xs-2 col-sm-1 col-md-2');
}
});
} else {
$topicTitle.attr('class', 'topic-title col-sm-4 col-md-5');
$topic.find('.topics-subject').attr('class', 'topics-subject col-xs-7 col-sm-4 col-md-5');
$topic.find('.topics-users').attr('class', 'topics-users col-sm-2 col-md-3');
}
} else if ( !hasCategories ) {
$topicTitle.attr('class', 'topic-title col-sm-6');
$topic.find('.topics-subject').attr('class', 'topics-subject col-xs-7 col-sm-6');
}
});
}
function initializeMoreTopics( data, $container, $moreTopics, w, websiteID, itemUniqueID, hasCategories ) {
initializeTopics(data,$container,$moreTopics,w,websiteID,itemUniqueID,hasCategories);
$container.find('.forum-load-more-loading').remove();
$moreTopics.find('.forum-topic').each(function(){
$container.append($(this));
});
$container.data('is-loading','false');
}
function initializeForumTopics( data, $container, $moreTopics, w, websiteID, itemUniqueID, hasCategories ) {
initializeTopics(data,$container,$moreTopics,w,websiteID,itemUniqueID,hasCategories);
generateAddNewTopicBtn(data,$container,$moreTopics,w,websiteID,itemUniqueID);
Forum_updateActivityDateTime($container.data('date-time'),$container.find('.topic-last-activity'));
$container.find('.forum-avatar').each(function(key,value){
Forum_initializeClientCard($(value),websiteID,w,itemUniqueID);
});
}
/**
* The function generate buttons for the main topics page
*/
function generateAddNewTopicBtn( data, $container, $topics, w, websiteID, itemUniqueID ) {
var $newTopicBtn = $container.find('.add-new-topic-btn');
var categories = $container.data('categories');
var loginURL = $container.data('login-url');
var categoryID = $container.data('category-id') ? $container.data('category-id') : '';
if ( data.loggedIn == 'true' ) {
initializeAddNewTopicBtn(websiteID,itemUniqueID,$newTopicBtn,categories,categoryID);
} else {
$newTopicBtn.attr('href', loginURL);
}
}
/**
* The function initialize buttons
* @param {string} websiteID - Website ID
* @param {string} itemUniqueID - Module unique ID
* @param {object} $button - Button
* @param {object} categories - Categories list
* @param {string} categoryID - Category ID
*/
function initializeAddNewTopicBtn( websiteID, itemUniqueID, $button, categories, categoryID ) {
var $addTopicBtn = $button;
$addTopicBtn.off('click').click(function() {
var w = $('#w').val();
buildPopup('popupNewTopic','',buildNewTopicForm(websiteID,w,itemUniqueID),'',true,false,true,'','');
Forum_ActiveSoftLabelInputs();
var $popup = $('#popupNewTopic');
var $loading = $popup.find('#loading');
generateCategoriesBox($popup,categories);
if ( categoryID.length > 0 ) {
$popup.find('select[name=categoryUniqueID]').val(categoryID);
}
Forum_froalaEditorInit($popup,false);
$popup.find('input[name=subject]').focus();
$popup.find('.newTopicForm').each( function( index ) {
var $form = $(this);
/**
* jQuery Validation Plugin Initial
* Documentation : http://jqueryvalidation.org/documentation/
*/
$form.validate({
errorElement: 'div',
errorClass: 'help-block',
focusInvalid: true,
ignore: "",
highlight: function (e) {
$(e).closest('.form-group').removeClass('has-info').addClass('has-error');
},
success: function (e) {
$(e).closest('.form-group').removeClass('has-error');
$(e).remove();
},
submitHandler: function( form ) {
var $form = $(form);
$form.find('button:submit').prop('disabled', true);
$form.hide();
$loading.show();
$.ajax({
type: "POST",
url: "/versions/"+$('#versionNUM').val()+"/wizard/modules/forum/addTopic.php",
data: $form.serialize(),
success: function( data ) {
var dataObj = jQuery.parseJSON(data);
$loading.hide();
if ( dataObj.status == 'done' ) {
$form.trigger("reset");
buildPopup_CloseAction('popupNewTopic');
if ( dataObj.url.length === 0 ) location.reload();
window.location.href = dataObj.url;
} else {
$form.find('button:submit').prop('disabled', false);
$form.show();
return false;
}
}
});
}
});
});
});
}
/**
* The function initialize buttons
* @param {string} websiteID - Website ID
* @param {string} topicID - Topic ID
* @param {string} itemUniqueID - Module unique ID
* @param {object} $html - Buttons object
*/
function initializeTopicsButtons ( websiteID, topicID, itemUniqueID, $html ) {
if ( !$html ) return;
var $rmvTopicBtn = $html.find('.rmv-topic-btn');
$rmvTopicBtn.off('click').click(function() {
var w = $('#w').val();
bootbox.confirm({
title: ''+translations.forumDeleteTopicTitle+'',
message: translations.forumDeleteTopic,
backdrop: true,
buttons: {
confirm: {
label: translations.yes,
className: 'btn-danger'
},
cancel: {
label: translations.no,
className: 'btn-default'
}
},
callback: function( result ) {
if ( !result ) return;
$.ajax({
type: "POST",
url: "/versions/"+$('#versionNUM').val()+"/wizard/modules/forum/rmvTopic.php",
data: 'w='+w+'&websiteID='+websiteID+'&uniqueID='+topicID+'&itemUniqueID='+itemUniqueID,
success: function( data ) {
var dataObj = jQuery.parseJSON(data);
if ( dataObj.status == 'done' ) window.location.reload();
}
});
}
});
});
}
/**
* The function build the html of the new topic form
*
* @param {string} websiteID - Website ID.
* @param {string} w - Website ID.
* @param {string} itemUniqueID - Module unique ID.
* @return {string} html - Html of the reply form.
*/
function buildNewTopicForm(websiteID, w, itemUniqueID) {
var direction = $('html').attr('dir') === 'rtl' ? 'right' : 'left';
var html = '';
html += '
';
html += '';
html += '
';
return html;
}
/**
* This function generate the categories select box
*
* @param {object} $popup - Popup jQuery object
* @param {object} categories - Categories
*/
function generateCategoriesBox( $popup, categories ) {
var options = '';
$.each (categories, function (categoryUniqueID, category) {
options += '';
});
if ( options.length === 0 ) return;
var html = '';
html += '
';
html += '';
html += '';
html += '
';
$html = $(html);
$popup.find('.categories-list').append($html).show();
}
function generateForumInfoPopUp( w, websiteID, categoryUniqueID ) {
var html = '
';
html += '
';
html += '
';
html += '
';
html += '
';
html += '';
html += '
';
html += '
';
html += '
';
html += '
';
html += '
';
buildPopup('popupForumInformation','',html,'',true,false,true,'','');
var $popupForumInformation = $('#popupForumInformation');
var $loading = $popupForumInformation.find('#loading');
$.ajax({
type: "POST",
url: "/versions/"+$('#versionNUM').val()+"/wizard/modules/forum/getForumInfo.php",
data: 'w='+w+'&websiteID='+websiteID+'&categoryUniqueID='+categoryUniqueID,
beforeSend: function(){
$loading.show();
},
complete: function(){
$loading.hide();
},
success: function( data ) {
var data = jQuery.parseJSON(data);
$popupForumInformation.find('.forum-information').append($(data.info));
}
});
}jQuery(function($) {
ForumExpandedSearchInitialize();
});
/**
* The function initialize forum expanded search
*/
function ForumExpandedSearchInitialize() {
$( document ).on( 's123.page.ready', function( event ) {
var w = $('#w').val();
var $section = $('section.s123-module-forum.forum-expanded-search');
$section.each(function( index ) {
var $sectionThis = $(this);
var $forumSearchContainer = $sectionThis.find('.forum-search-container');
var $forumResultscontainer = $sectionThis.find('.forum-results-container');
var $container = $sectionThis.find('.expanded-search-container');
var websiteID = $container.data('website-id');
var itemUniqueID = $container.data('module-unique-id');
var dateTime = $container.data('date-time');
$sectionThis.find('.forum-search-form').each( function( index ) {
var $form = $(this);
var $searchInput = $form.find('[name=q]');
var $datepicker = $form.find('.datepicker');
var $advancedSearch = $form.find('.forum-advanced-search');
var $advancedSearchBtn = $form.find('.forum-advanced-search-btn');
$searchInput.focus();
/**
* Get the section date time picker
* API: https://github.com/uxsolutions/bootstrap-datepicker
*/
$datepicker.datepicker({
format: 'mm/dd/yyyy',
todayBtn: 'linked'
}).datepicker('setDate', new Date());
/**
* jQuery Validation Plugin Initial
* Documentation : http://jqueryvalidation.org/documentation/
*/
$form.validate({
errorElement: 'div',
errorClass: 'help-block',
focusInvalid: true,
ignore: "",
highlight: function (e) {
$(e).closest('.form-group').removeClass('has-info').addClass('has-error');
},
success: function (e) {
$(e).closest('.form-group').removeClass('has-error');
$(e).remove();
},
submitHandler: function( form ) {
var $form = $(form);
$form.find('button:submit').prop('disabled', true);
$.ajax({
type: "POST",
url: "/versions/"+$('#versionNUM').val()+"/wizard/modules/forum/search.php",
data: $form.serialize(),
beforeSend: function(){
$forumResultscontainer.html('');
$forumSearchContainer.find('.forum-search-loading').show();
},
complete: function(){
$forumSearchContainer.find('.forum-search-loading').hide();
},
success: function( data ) {
var dataObj = jQuery.parseJSON(data);
if ( dataObj.status == 'fail' ) {
$forumResultscontainer.html('
' + dataObj.msg + '
').show();
}
if ( dataObj.status == 'good' ) {
initializeForumSearchResults(dataObj,$forumResultscontainer,dateTime);
$forumResultscontainer.find('.forum-avatar').each(function(key,value){
Forum_initializeClientCard($(value),websiteID,w,itemUniqueID);
});
$forumResultscontainer.slideDown(200);
}
$form.find('button:submit').prop('disabled', false);
}
});
return false;
}
});
if ( $searchInput.val().length > 0 ) $form.submit();
$advancedSearchBtn.off('click').on('click', function() {
$advancedSearch.slideToggle('slow');
return false;
});
});
});
});
}
/**
* The function generate expanded search results
*
* @result {string} html - Search result HTML
*/
function generateForumSearchResult() {
var html = '
';
html += '
';
html += '
';
html += '
';
html += '';
html += '
';
html += '
';
html += '
';
html += '
';
html += '';
html += '';
html += '
';
html += '
';
html += '
';
html += '
';
return html;
}
/**
* The function generate expanded search results
*
* @param {object} results - Forum expanded search results
* @param {object} $container - Search results container in jQuery object
* @result {object} $html - Search results HTML in jQuery object
*/
function initializeForumSearchResults( dataObj, $container, dateTime ) {
dateTime = new Date(dateTime);
var html = '
';
html += '
';
html += '' + dataObj.results.length + ' ' + dataObj.msg + ' ';
html += '' + dataObj.query + '';
html += '
';
html += '';
html += '
';
var $html = $(html);
$container.append($html);
$.each(dataObj.results, function(key,result) {
var html = generateForumSearchResult();
var $html = $(html);
$html.find('.f-search-post-title a').attr('href',result.url).html(result.subject);
$html.find('.f-search-post-message').html(result.message);
$html.find('.f-search-client-avatar').append(Forum_setAvatar(result.avatar[0].image,100,result.avatar[0].name,result.avatar[0].color));
$html.find('.f-search-client-avatar .avatar-img').addClass('forum-avatar').attr('data-client-id',result.avatar[0].id);
if ( result.categoryName != null && result.categoryName.length > 0 ) $html.find('.f-search-category span b').html(result.categoryName).show();
var createTime = new Date(result.createTime);
var diff = dateTime - createTime;
$html.find('.f-search-post-time').data('date-time',result.createTime).html(Forum_calcActivityTime(diff,createTime));
$container.append($html);
});
}jQuery(function($) {
var rtl = $('html[dir=rtl]').length === 1;
var $section = $('section.s123-page-data-forum');
var $postDateTime = $section.find('.post-date-time');
var $shareReplyBtn = $section.find('.share-reply-btn');
var $topicContainer = $section.find('.topic-container');
var $buttonsContainer = $section.find('.reply-buttons-container');
var $suggestedTopics = $section.find('.f-suggested-topics');
var $mainTopic = $topicContainer.find('.forum-main-topic');
var $replies = $topicContainer.find('.f-replies');
var itemUniqueID = $topicContainer.data('module-unique-id');
var categoryUniqueID = $topicContainer.data('category-id') ? $topicContainer.data('category-id') : '' ;
var topicUniqueID = $topicContainer.data('unique-id');
var loginURL = $topicContainer.attr('data-login-url');
var websiteID = $topicContainer.data('website-id');
var dateTime = $topicContainer.data('date-time');
var searchURL = $topicContainer.data('search-url');
var w = $('#w').val();
var replyID = $topicContainer.data('reply-id');
var topicURL = $topicContainer.data('topic-url');
var customLabels = $('.custom-labels').val();
if ( $section.length === 0 ) return;
customLabels = jQuery.parseJSON(customLabels);
$.ajax({
type: "POST",
url: "/versions/"+$('#versionNUM').val()+"/wizard/modules/forum/getTopicData.php",
data: 'w='+w+'&websiteID='+websiteID+'&uniqueID='+topicUniqueID+'&categoryUniqueID='+categoryUniqueID,
success: function( data ) {
var dataObj = jQuery.parseJSON(data);
dateTime = dataObj.time;
$buttonsContainer.each(function(index,buttonContainer) {
var $buttonContainer = $(buttonContainer);
var replyUniqueID = $buttonContainer.attr('data-reply-id') ? $buttonContainer.data('reply-id') : '';
var $html = generateButtonsHTML(websiteID,topicUniqueID,itemUniqueID,dataObj,loginURL,replyUniqueID,index,customLabels);
initializeButtons(websiteID,topicUniqueID,categoryUniqueID,$html,topicURL);
$buttonContainer.prepend($html);
});
Forum_updateActivityDateTime(dateTime,$postDateTime);
displayEditPostBtn(dateTime,$postDateTime,dataObj);
var $sideMenuContainer = generateTopicSideMenu(dataObj,topicUniqueID,$topicContainer,websiteID,topicUniqueID,w,dateTime,itemUniqueID,customLabels);
$topicContainer.append($sideMenuContainer);
var topicsContainersHeight = $('#topicBox').outerHeight(); // OLD CODE: $replies.outerHeight() + $mainTopic.outerHeight();
var sideMenuContainerHeight = $sideMenuContainer.outerHeight();
updateSideMenuPosition($sideMenuContainer,topicsContainersHeight,sideMenuContainerHeight);
$(window).scroll(function() {
updateSideMenuPosition($sideMenuContainer,topicsContainersHeight,sideMenuContainerHeight);
});
Forum_initializeSearch($section,websiteID,itemUniqueID,searchURL,dateTime);
$topicContainer.find('.topic-buttons').append(generateSmallTopicMenu(dataObj,topicUniqueID,$topicContainer,websiteID,topicUniqueID,w,dateTime,searchURL,customLabels));
}
});
shareBtnClickEvent($shareReplyBtn);
$section.find('.forum-avatar').each(function(key,value){
Forum_initializeClientCard($(value),websiteID,w,itemUniqueID);
});
Forum_updateActivityDateTime(dateTime, $suggestedTopics.find('.topic-last-activity'));
increaseTopicViews(w,websiteID,topicUniqueID);
if ( replyID.length > 0 ) {
scrollToReply(replyID);
}
});
/**
* The function scroll the page to the new reply.
*/
function scrollToReply( replyID ) {
if ( $('#'+replyID).length === 0 ) return;
$('html, body').animate({
scrollTop: $('#'+replyID).offset().top
}, 1000);
}
/**
* Generate topic side menu generate
*/
function generateSmallTopicMenu( topicData, topicUniqueID, $topicContainer, websiteID, uniqueID, w, dateTime, searchURL, customLabels) {
var html = '
';
}
}
$html = $(html);
return $html;
}
/**
* The function initialize buttons
* @param {string} websiteID - Website ID
* @param {string} itemUniqueID - Module unique ID
* @param {string} uniqueID - Topic unique ID
* @param {object} $html - Buttons container jQuery object
*/
function initializeButtons( websiteID, uniqueID, categoryUniqueID, $html, topicURL ) {
var w = $('#w').val();
var $addReplyBtn = $html.find('.add-reply-btn');
var $rmvReplyBtn = $html.find('.rmv-reply-btn');
var $editBtn = $html.find('.edit-btn');
var $shareReplyBtn = $html.find('.share-reply-btn');
(function(){
$addReplyBtn.click(function() {
buildPopup('popupTopicReply','',buildReplyForm(websiteID,uniqueID,w,''),'',true,false,true,'','');
var $popup = $('#popupTopicReply');
var $loading = $popup.find('#loading');
Forum_froalaEditorInit($popup,true);
$popup.find('.replyForm').each( function( index ) {
var $form = $(this);
/**
* jQuery Validation Plugin Initial
* Documentation : http://jqueryvalidation.org/documentation/
*/
$form.validate({
errorElement: 'div',
errorClass: 'help-block',
focusInvalid: true,
ignore: "",
highlight: function (e) {
$(e).closest('.form-group').removeClass('has-info').addClass('has-error');
},
success: function (e) {
$(e).closest('.form-group').removeClass('has-error');
$(e).remove();
},
submitHandler: function( form ) {
var $form = $(form);
$form.find('button:submit').prop('disabled', true);
$form.hide();
$loading.show();
$.ajax({
type: "POST",
url: "/versions/"+$('#versionNUM').val()+"/wizard/modules/forum/addReply.php",
data: $form.serialize(),
success: function( data ) {
var dataObj = jQuery.parseJSON(data);
$loading.hide();
if ( dataObj.status == 'done' ) {
$form.trigger("reset");
buildPopup_CloseAction('popupTopicReply');
if ( dataObj.replyID.length > 0 ) {
window.location.href = topicURL + dataObj.replyID;
} else {
location.reload();
}
} else {
$form.find('button:submit').prop('disabled', false);
$form.show();
return false;
}
}
});
}
});
});
});
$editBtn.click(function() {
$bth = $(this);
postID = $bth.attr('data-reply-id') ? $bth.data('reply-id') : uniqueID ;
$.ajax({
type: "POST",
url: "/versions/"+$('#versionNUM').val()+"/wizard/modules/forum/getContent.php",
data: 'w='+w+'&websiteID='+websiteID+'&postID='+postID+'',
success: function( data ) {
var dataObj = jQuery.parseJSON(data);
if ( dataObj.message.length > 0 ) {
buildPopup('popupEditTopicReply','',buildReplyForm(websiteID,postID,w,dataObj),'',true,false,true,'','');
Forum_ActiveSoftLabelInputs();
var $popup = $('#popupEditTopicReply');
var $loading = $popup.find('#loading');
generatePostCategoriesBox($popup,dataObj);
if ( dataObj.subject && dataObj.subject.length > 0 ) {
$popup.find('input[name=subject]').focus();
Forum_froalaEditorInit($popup,false);
} else {
Forum_froalaEditorInit($popup,true);
}
$popup.find('.replyForm').each( function( index ) {
var $form = $(this);
/**
* jQuery Validation Plugin Initial
* Documentation : http://jqueryvalidation.org/documentation/
*/
$form.validate({
errorElement: 'div',
errorClass: 'help-block',
focusInvalid: true,
ignore: "",
highlight: function (e) {
$(e).closest('.form-group').removeClass('has-info').addClass('has-error');
},
success: function (e) {
$(e).closest('.form-group').removeClass('has-error');
$(e).remove();
},
submitHandler: function( form ) {
var $form = $(form);
$form.find('button:submit').prop('disabled', true);
$form.hide();
$loading.show();
$.ajax({
type: "POST",
url: "/versions/"+$('#versionNUM').val()+"/wizard/modules/forum/editPost.php",
data: $form.serialize(),
success: function( data ) {
var dataObj = jQuery.parseJSON(data);
if ( dataObj.status == 'done' ) {
$form.trigger("reset");
$form.find('button:submit').prop('disabled', false);
$loading.hide();
buildPopup_CloseAction('popupEditTopicReply');
location.reload();
}
}
});
$form.find('button:submit').prop('disabled', false);
$loading.hide();
buildPopup_CloseAction('popupEditTopicReply');
return false;
}
});
});
}
}
});
});
if ( $rmvReplyBtn.length === 0 ) return;
$rmvReplyBtn.click(function() {
var replyUniqueID = $(this).data('reply-id');
if ( replyUniqueID.length === 0 ) return;
bootbox.confirm({
title: ''+translations.forumDeleteReplyTitle+'',
message: translations.forumDeleteReply,
backdrop: true,
buttons: {
confirm: {
label: translations.yes,
className: 'btn-danger'
},
cancel: {
label: translations.no,
className: 'btn-default'
}
},
callback: function( result ) {
if ( !result ) return;
$.ajax({
type: "POST",
url: "/versions/"+$('#versionNUM').val()+"/wizard/modules/forum/rmvReply.php",
data: 'w='+w+'&websiteID='+websiteID+'&topicID='+uniqueID+'&replyID='+replyUniqueID+'&categoryUniqueID='+categoryUniqueID,
success: function( data ) {
var dataObj = jQuery.parseJSON(data);
if ( dataObj.status == 'done' ) window.location.reload();
}
});
}
});
});
})();
}
/**
* The function build the HTML of the reply form
*
* @param {string} websiteID - Website ID.
* @param {string} w - Website ID.
* @param {string} uniqueID - Unique item ID.
* @param {object} post - Post object.
* @return {string} html - Html of the reply form.
*/
function buildReplyForm( websiteID, uniqueID, w, post ) {
var direction = $('html').attr('dir') === 'rtl' ? 'right' : 'left';
var message = post.message ? post.message : '';
var html = '';
html += '
';
html += '';
html += '
';
return html;
}
/**
* The function display the edit button for each post that the client can edit.
* Client can edit post content in the first 24 hours only.
*
* @param {string} dateTime - Date and time according to the website timezone
* @param {object} $posts - Posts jQuery object
* @param {object} $dataObj - Topic data
*/
function displayEditPostBtn( dateTime, $posts, dataObj ) {
var oneDay = 24 * 60 * 60 * 1000
dateTime = new Date(dateTime);
$posts.each(function (index, post) {
var $post = $(post);
if ( dataObj.clientID == $post.closest('.post').data('client-id') ) {
var postDateTime = new Date($post.data('date-time'));
var diff = dateTime - postDateTime;
if ( diff < oneDay ) $post.closest('.post').find('.reply-buttons-container .edit-btn-container').show();
}
});
}
/**
* This function generate the categories select box
*
* @param {object} $popup - Popup jQuery object
* @param {object} post - Post object
*/
function generatePostCategoriesBox( $popup, post ) {
var options = '';
var hasCategories = false;
$.each (post.categories, function (categoryUniqueID, category) {
options += '';
hasCategories = true;
});
if ( options.length === 0 ) return;
var html = '';
html += '
';
html += '';
html += '';
html += '
';
$html = $(html);
if ( post.categoryUniqueID ) {
$html.find('option[value='+post.categoryUniqueID+']').prop('selected','ture');
}
if ( hasCategories ) $popup.find('.categories-list').append($html).show();
}
/**
* This function update the side menu position according to the window scroll position
*/
function updateSideMenuPosition( $sideMenu, topicsHeight, sideMenuHeight ) {
var windowScrollTop = $(window).scrollTop();
if ( windowScrollTop >= topicsHeight-sideMenuHeight ) {
$sideMenu.css('top',topicsHeight-sideMenuHeight);
} else {
$sideMenu.css('top',windowScrollTop);
}
}
/**
* This function increase the topic views only if it's not a bot
*/
function increaseTopicViews(w,websiteID,topicUniqueID){
$.post('/versions/2/wizard/modules/forum/topicViewsAJAX.php', {
w: w,
websiteID: websiteID,
topicUniqueID: topicUniqueID
});
}jQuery(function($) {
ForumModuleInitialize_Layout2();
});
/**
* The function initialize forum module layout 2
*/
function ForumModuleInitialize_Layout2() {
$( document ).on( 's123.page.ready', function( event ) {
var w = $('#w').val();
var $section = $('section.s123-module-forum.layout-2 .forum-topics-list');
$section.each(function( index ) {
var $sectionThis = $(this);
var $loading = $sectionThis.find('.loading');
var $topFive = $sectionThis.find('.forum-top-five');
var websiteID = $sectionThis.data('website-id');
var uniqueID = $sectionThis.data('module-unique-id');
if ( $sectionThis.length > 0 ) {
$.ajax({
type: "POST",
url: "/versions/"+$('#versionNUM').val()+"/wizard/modules/forum/getForumTopics.php",
data: 'w='+w+'&websiteID='+websiteID+'&categoryUniqueID=&uniqueID='+uniqueID,
success: function( data ) {
$data = $(data);
$loading.hide();
$section.html('').append($data.hide().fadeIn(200));
}
});
}
});
});
}/*!
* jQuery Cookie Plugin v1.4.1
* https://github.com/carhartl/jquery-cookie
*
* Copyright 2006, 2014 Klaus Hartl
* Released under the MIT license
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('jquery'));
} else {
factory(jQuery);
}
}(function ($) {
var pluses = /\+/g;
function encode(s) {
return config.raw ? s : encodeURIComponent(s);
}
function decode(s) {
return config.raw ? s : decodeURIComponent(s);
}
function stringifyCookieValue(value) {
return encode(config.json ? JSON.stringify(value) : String(value));
}
function parseCookieValue(s) {
if (s.indexOf('"') === 0) {
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
try {
s = decodeURIComponent(s.replace(pluses, ' '));
return config.json ? JSON.parse(s) : s;
} catch(e) {}
}
function read(s, converter) {
var value = config.raw ? s : parseCookieValue(s);
return $.isFunction(converter) ? converter(value) : value;
}
var config = $.cookie = function (key, value, options) {
if (arguments.length > 1 && !$.isFunction(value)) {
options = $.extend({}, config.defaults, options);
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setMilliseconds(t.getMilliseconds() + days * 864e+5);
}
return (document.cookie = [
encode(key), '=', stringifyCookieValue(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
var result = key ? undefined : {},
cookies = document.cookie ? document.cookie.split('; ') : [],
i = 0,
l = cookies.length;
for (; i < l; i++) {
var parts = cookies[i].split('='),
name = decode(parts.shift()),
cookie = parts.join('=');
if (key === name) {
result = read(cookie, value);
break;
}
if (!key && (cookie = read(cookie)) !== undefined) {
result[name] = cookie;
}
}
return result;
};
config.defaults = {};
$.removeCookie = function (key, options) {
$.cookie(key, '', $.extend({}, options, { expires: -1 }));
return !$.cookie(key);
};
}));var eCommerceFilterTool = new function() {
var filter = this;
this.init = function ( settings ) {
if ( !settings ) return;
filter.productsContainerSelector = '.products-container';
filter.container = $('.e-commerce-filter-container');
filter.$scrollTo = $('.s123-module-eCommerce');
filter.isActive = settings.isActive;
filter.products = settings.products;
filter.currency = settings.currency;
filter.filteredProducts = false;
filter.translations = settings.translations;
filter.deviceType = findBootstrapEnvironment() === 'xs' ? 'mobile' : 'pc';
filter.w = settings.w;
filter.websiteID = settings.websiteID;
filter.type = settings.type;
filter.uniquePageID = settings.uniquePageID;
filter.filterCombinations = {};
filter.eCommerceSearch = settings.eCommerceSearch;
/**
* Security - We won't build the filter tool if 1 of the following conditions is true:
* 1. Filter tool is disabled.
* 2. No filter container.
*/
if ( !filter.isActive || !filter.container ) return;
filter.brands = settings.brands;
filter.price = settings.price;
filter.pOptions = settings.pOptions;
filter.pAttributes = settings.pAttributes;
filter.ribbons = settings.ribbons;
filter.addFilterTool();
/**
* By default the filter boxes are closed in any device and only in `pc` we are opening them
* if the user has choose to open them we do that by calling the method `closeOpenBox`
* and sending it all the expand icons.
*/
if ( filter.deviceType == 'pc' ) {
filter.container.css({'display': 'flex', 'flex-direction': 'column'});
var $allFilterBoxes = filter.container.find('.filter-options');
$.each($allFilterBoxes, function( index, box ) {
var $box = $(box);
if ( $box.data('def-state') === 'opened') {
$box.find('filter-option-content').addClass('expanded');
filter.closeOpenBox($box.find('.expand-filter'),0);
}
});
}
filter.addShowFilterMobileBtn();
filter.mobileFilterBtnResponsiveHandler();
};
/**
* The function handle the mobile response filter on windows resize, we need to show
* and hide it related to the user resolution.
*/
this.mobileFilterBtnResponsiveHandler = function() {
$(window).one('resize.eCommerceFilterToolMobileFilter', function( event ) {
filter.adaptToScreenSize();
setTimeout( function() {
filter.mobileFilterBtnResponsiveHandler();
},500);
});
}
/**
* The function is adapting the filter to the device screen, we need this because the structure if the
* filter tool is different between pc and mobile
*/
this.adaptToScreenSize = function() {
if ( $(window).width() > 767 ) {
filter.container.css({
display: 'flex',
flexDirection: 'column'
});
/* on mobile button click we save the container parent because we want to return
the container to it's place if the user is changing the screen size */
if ( filter.containerParent ) filter.containerParent.append(filter.container);
$('#ecommerceFilterMenuPopup').remove();
} else {
/* the resize event is called event when the user is scrolling to down
for example on iphone it is called when the bottom nav bar is hiding and this event
we want to ignore by checking if the filter is not in the popup because we are saving the filter parent
after the click on the mobile filter button */
if ( filter.containerParent ) return;
filter.container.css({
display: 'none',
flexDirection: ''
});
}
};
/**
* The method will return the filter box state from the cookie or false if there is no property for that
* filter box in the cookie.
*
* @param {integer} id - The filter box id
* @return {string} state - The filter state that were saved in the cookie or false
*/
this.getBoxStateFromCookie = function( id ) {
var eCommerceFilterBoxState = tryParseJSON($.cookie(filter.websiteID+'_eCommerceFilterBoxState'));
if ( !eCommerceFilterBoxState ) return false;
if ( !eCommerceFilterBoxState[id] ) return false;
return eCommerceFilterBoxState[id].state;
};
/**
* The method is responsible for saving all the boxes state to the cookie
*/
this.saveBoxesStateToCookie = function() {
var eCommerceFilterBoxState = {};
var $allFilterBoxes = filter.container.find('.filter-options');
$.each($allFilterBoxes, function( index, box ) {
var $box = $(box);
eCommerceFilterBoxState[$box.data('id')] = {
state: $box.find('.filter-option-content.expanded').length ? 'opened' : 'closed'
}
});
$.cookie(filter.websiteID+'_eCommerceFilterBoxState',JSON.stringify(eCommerceFilterBoxState),{ expires: 1, path: '/' });
};
/**
* The method is responsible for adding a mobile button that will show and
* hide the filter popup menu.
*/
this.addShowFilterMobileBtn = function() {
var $mobileBtnContainer = $('');
$mobileBtnContainer.insertBefore(filter.container);
filter.$mobileBtn = $mobileBtnContainer.find('.mobile-filter-btn');
filter.$mobileBtn.on('click', function() {
var $customCover = $('');
var $ecommerceFilterMenuPopup = $('#ecommerceFilterMenuPopup');
if ( $ecommerceFilterMenuPopup.length == 0 ) {
filter.containerParent = filter.container.parent();
buildPopup('ecommerceFilterMenuPopup','','','',true,true,true,'');
$ecommerceFilterMenuPopup = $('#ecommerceFilterMenuPopup');
$ecommerceFilterMenuPopup.find('.page').append(filter.container);
$ecommerceFilterMenuPopup.append($customCover);
filter.container.css({'display': 'flex', 'flex-direction': 'column'});
$ecommerceFilterMenuPopup.find('.popupCloseButton').off('click').on('click', function() {
$ecommerceFilterMenuPopup.removeClass('open');
});
$customCover.on('click', function() {
$ecommerceFilterMenuPopup.removeClass('open');
});
$ecommerceFilterMenuPopup.find('.cover').off('click').on('click', function() {
$ecommerceFilterMenuPopup.removeClass('open');
});
} else {
$ecommerceFilterMenuPopup.addClass('open');
}
});
};
/**
* The method is adding the filters type
* if they are set and active.
*/
this.addFilterTool = function() {
filter.addTagsContainer();
filter.addPriceFilter();
filter.addBrandsFilter();
filter.addProductOptionsFilter();
filter.addProductAttributesFilter();
filter.addRibbonsFilter();
filter.resetProductsCounter();
filter.addExpandBoxEvent();
};
/**
* The method is adding a container for the tags
*
* Note: The tags are actually the filter it self
* so if there will be no tags the tool will not work.
*/
this.addTagsContainer = function() {
var html = '';
html = '
';
html += '
';
html += '' + filter.translations.filterBy + '';
html += '';
html += '
';
html += '
';
filter.container.append(html);
filter.$tags = filter.container.find('.filter-tags-container .tags');
};
/**
* The method is rounding the number to the closest decimal number
* for example if the price is 14 it will be rounded to 40 and if the number is
* 16 it will be rounded to 20.
*
* formula:
* 1. var number = 14;
* 2. var ceil = (Math.ceil(number / 10) * 10) `the result is 20`
* 3. ceil - number; `the result is 6`
* 4.
* @param {Integer} number - The number we want to round.
* @return {Integer} number - The rounded result of the number.
*/
this.floorCeilPrice = function( number ) {
var ceil = (Math.ceil(number / 10) * 10);
var complete = ceil - number;
if ( complete > 5 ) {
number = Math.floor(number / 10) * 10;
} else if ( complete < 5 ) {
number = Math.ceil(number / 10) * 10;
} else {
number = number;
}
return number;
};
/**
* The method is adding the price filter option to
* the filter tool.
*/
this.addPriceFilter = function() {
if ( !filter.price.active ) return;
/**
* Get the value we need to increase the range inside the loop
* and also make sure that the numbers are rounded.
*/
var rangeIncrease = filter.price.rangeIncrease;
var range = filter.floorCeilPrice((parseFloat(filter.price.min) + rangeIncrease));
var template = filter.getFilterBoxTemplate();
var defState = filter.getBoxStateFromCookie('price');
var html = '';
filter.price.max = (Math.ceil(filter.price.max / 10) * 10);
/**
* If the range increase steps are 0 it means there is no need to show price filter
* because all product has the same price.
*/
if ( rangeIncrease > 0 ) {
template = template.replace('{{place}}',filter.price.place);
template = template.replace('{{title}}',filter.translations.priceTitle);
template = template.replace('{{class}}','filter-type-price');
template = template.replace('{{type}}','price');
template = template.replace('{{id}}','price');
template = template.replace('{{defState}}',(defState ? defState : filter.price.filterBoxState));
html += '
';
template = template.replace('{{content}}',html);
filter.container.append(template);
filter.addPriceEvent();
}
};
/**
* The method is adding the brands filter option to the filter tool.
*/
this.addBrandsFilter = function() {
if ( !filter.brands.active ) return;
var template = filter.getFilterBoxTemplate();
var defState = filter.getBoxStateFromCookie('brands-system-id');
var html = '';
template = template.replace('{{place}}',(parseInt(filter.brands.place)));
template = template.replace('{{title}}',filter.translations.brandsTitle);
template = template.replace('{{class}}','filter-type-brands');
template = template.replace('{{type}}','brand');
template = template.replace('{{id}}','brands-system-id');
template = template.replace('{{defState}}',(defState ? defState : filter.brands.filterBoxState));
$.each(filter.brands.values, function( index, brand ) {
brand.allSettings = JSON.parse(brand.allSettings);
var obj = {
title : brand.allSettings.title,
value : index,
dataAttr: 'data-type="brand" data-unique-id="' + escapeHtml(index) + '" data-parent-unique-id="brands-system-id"'
}
html += filter.generateCheckBox(obj);
html = html.replace('{{placeStyle}}','style="order:' + escapeHtml(brand.place) + '";');
});
template = template.replace('{{content}}',html);
filter.container.append(template);
filter.addCheckBoxEvent();
};
/**
* The method is adding the product options filter
* to the page.
*/
this.addProductOptionsFilter = function() {
if ( !filter.pOptions.active ) return;
$.each(filter.pOptions.options, function( index, po ) {
var template = filter.getFilterBoxTemplate();
var defState = filter.getBoxStateFromCookie(po.id);
var html = '';
template = template.replace('{{place}}',(parseInt(po.place)));
template = template.replace('{{title}}',po.title);
template = template.replace('{{class}}','filter-type-options');
template = template.replace('{{type}}',po.type);
template = template.replace('{{id}}',escapeHtml(po.id));
template = template.replace('{{defState}}',(defState ? defState : po.filterBoxState));
$.each(po.items, function( index, item ) {
if ( po.type == 'color' ) {
var obj = {
title : item.title,
value : item.color,
dataAttr: 'data-type="' + escapeHtml(po.type) + '" data-unique-id="' + escapeHtml(item.color) + '" data-parent-unique-id="' + escapeHtml(po.id) + '"',
imgSrc: item.imgSrc
}
html += filter.generateColor(obj);
} else {
var obj = {
title : item.title,
value : item.id,
dataAttr: 'data-type="' + escapeHtml(po.type) + '" data-unique-id="' + escapeHtml(item.id) + '" data-parent-unique-id="' + escapeHtml(po.id) + '"',
imgSrc: item.imgSrc
}
html += filter.generateCheckBox(obj);
html = html.replace('{{placeStyle}}','');
}
});
template = template.replace('{{content}}',html);
filter.container.append(template);
});
/**
* Bootstrap Tooltip Initialize
* Documentation: https://v4-alpha.getbootstrap.com/components/tooltips/
*/
filter.container.find('.color').tooltip({
container: '.e-commerce-filter-container',
placement: 'top'
});
filter.addCheckBoxEvent();
filter.addColorBoxEvent();
};
/**
* The method is adding the product attributes filter
* to the page.
*/
this.addProductAttributesFilter = function() {
if ( !filter.pAttributes.active ) return;
$.each(filter.pAttributes.attributes, function( index, attr ) {
var template = filter.getFilterBoxTemplate();
var defState = filter.getBoxStateFromCookie(attr.id);
var html = '';
template = template.replace('{{place}}',(parseInt(attr.place)));
template = template.replace('{{title}}',attr.title);
template = template.replace('{{class}}','filter-type-attributes');
template = template.replace('{{type}}','attribute');
template = template.replace('{{id}}',escapeHtml(attr.id));
template = template.replace('{{defState}}',(defState ? defState : attr.filterBoxState));
$.each(attr.values, function( index, value ) {
var obj = {
title : value.title,
value : value.id,
dataAttr: 'data-type="' + escapeHtml(attr.type) + '" data-unique-id="' + escapeHtml(value.id) + '" data-parent-unique-id="' + escapeHtml(attr.id) + '"'
}
html += filter.generateCheckBox(obj);
html = html.replace('{{placeStyle}}','');
});
template = template.replace('{{content}}',html);
filter.container.append(template);
});
filter.addCheckBoxEvent();
};
/**
* The method is adding the ribbons filter to the page.
*/
this.addRibbonsFilter = function() {
if ( !filter.ribbons.active ) return;
var template = filter.getFilterBoxTemplate();
var defState = filter.getBoxStateFromCookie('ribbonsObj-system-id');
var html = '';
template = template.replace('{{place}}',filter.ribbons.place);
template = template.replace('{{title}}',filter.translations.ribbonsTitle);
template = template.replace('{{class}}','filter-type-ribbons');
template = template.replace('{{type}}','ribbon');
template = template.replace('{{id}}','ribbonsObj-system-id');
template = template.replace('{{defState}}',(defState ? defState : filter.ribbons.filterBoxState));
$.each(filter.ribbons.values, function( index, ribbon ) {
var obj = {
title : ribbon.title,
value : ribbon.id,
dataAttr: 'data-type="ribbon" data-unique-id="' + escapeHtml(ribbon.id) + '" data-parent-unique-id="ribbonsObj-system-id"'
}
html += filter.generateCheckBox(obj);
html = html.replace('{{placeStyle}}','');
});
template = template.replace('{{content}}',html);
filter.container.append(template);
filter.addCheckBoxEvent();
};
/**
* The method is reseting the product counter.
*/
this.resetProductsCounter = function() {
var $counters = filter.container.find('.products-in-filter');
var $filterOptions = filter.container.find('.filter-options');
var products = filter.filteredProducts ? filter.filteredProducts : filter.products;
$.each($counters, function( index, counter ) {
var $this = $(this);
$this.empty();
var $parent = $(this).parent();
switch( $parent.data('type') ) {
case 'brand':
var obj = {};
obj.val = $parent.data('unique-id');
break;
case 'ribbon':
var obj = {};
obj.val = $parent.data('unique-id');
break;
case 'price':
var obj = {};
obj.min = $parent.data('min');
obj.max = $parent.data('max');
break;
case 'color':
var obj = {};
obj.parentUniqueID = $this.data('parent-unique-id');
obj.val = $this.data('unique-id');
break;
default :
var obj = {};
obj.parentUniqueID = $this.data('parent-unique-id');
obj.val = $parent.data('unique-id');
break;
}
var result = filter.getProductByFilterType($parent.data('type'),obj,Array(),products);
/* If the current filter option has tool tip we need to refresh the counter inside of it,
at the moment only the colors are using this ability*/
if ( $parent.data('type') === 'color' ) {
var $color = $parent.find('.color');
$color.attr('data-original-title', $color.data('title') + ' ('+result.length+')');
filter.hideShowFilterOption($parent,$this,result.length);
} else {
filter.hideShowFilterOption($parent.parent(),$this,result.length);
}
});
/**
* When all of the filter option items don't have products
* we need to hide the filter option it self.
*/
$.each($filterOptions, function( index, option ) {
var $this = $(this);
var $counters = $this.find('.products-in-filter');
var $hiddenCounters = $counters.filter('[data-products-in-filter="0"]');
if ( $counters.length === $hiddenCounters.length ) {
$this.hide();
} else {
$this.show();
}
});
filter.hideShowFilterSiblings();
};
/**
* The method is hiding all of the elements with the same parent of the filter e.g collections.
* Notes:
* 1. We did that so the user will not be confused by other options in the side menu for example
* the collections.
* 2. We don't apply this rule on the filter mobile button because it is used for the mobile and it need
* always visible to the user.
*/
this.hideShowFilterSiblings = function() {
if ( filter.$tags.children('.tag').length === 0 ) {
filter.container.siblings(':not(.m-f-b-container)').fadeIn(200);
} else {
filter.container.siblings(':not(.m-f-b-container)').fadeOut(200);
}
};
/**
* The method is hiding or showing the filter option, if counter of the related products
* to the filter item is 0 the option will be hidden.
*
*@param {jquery object} $option - The option that we need to hide or show.
*@param {jquery object} $counter - The counter that we need to refresh.
*@param {integer} productsCounter - The related products counter to the filter option.
*/
this.hideShowFilterOption = function( $option, $counter, productsCounter ) {
if ( productsCounter == 0 ) {
$option.hide();
$counter.append(' (' + productsCounter + ')');
$counter.attr('data-products-in-filter',productsCounter);
} else {
$option.show();
$counter.append(' (' + productsCounter + ')');
$counter.attr('data-products-in-filter',productsCounter);
}
};
/**
* The method is generating color box html
* @param {Object} title - The object contains the filter option data such as title and more.
* @return {string} html - Color box html.
*/
this.generateColor = function( obj ) {
var html = '';
html += '';
return html;
};
/**
* The method is adding price filter event.
*
* Note: The price links are just adding the values to the
* filter inputs and triggering the button event.
*/
this.addPriceEvent = function() {
var $rangeOptions = filter.container.find('.range-filter');
var $filterByPriceBtn = filter.container.find('.filter-by-price-btn');
var $minPrice = filter.container.find('.minPrice');
var $maxPrice = filter.container.find('.maxPrice');
$rangeOptions.on('click', function() {
var $this = $(this);
$minPrice.val($this.data('min'));
$maxPrice.val($this.data('max'));
$rangeOptions.removeClass('selected-filter');
$this.addClass('selected-filter');
$filterByPriceBtn.trigger('click');
});
$filterByPriceBtn.on('click', function() {
filter.container.find('.filter-tags-container .tags .tag[data-type="price"]').remove();
var dataAttr = 'data-type="price" data-min="' + $minPrice.val() + '" data-max="' + $maxPrice.val() + '"';
var customTagText = $rangeOptions.filter('.selected-filter').data('custom-tag-text');
if ( customTagText ) {
filter.addFilterTag(customTagText,dataAttr);
} else {
filter.addFilterTag($minPrice.val()+'-'+$maxPrice.val(),dataAttr);
}
});
};
/**
* The method is generating html of the check boxes.
* @param {string} title - The check box text.
* @param {string} value - The check box value.
* @param {string} dataAttr - Additional data tributes.
* @return {string} html - Check box html.
*/
this.generateCheckBox = function( obj ) {
var html = '';
html += '
';
html += '';
html += '
';
return html;
};
/**
* The method is adding the tag of the filter to
* the tags container.
* @param {string} title - The check box text.
* @param {string} dataAttr - The tag data attributes as string.
*/
this.addFilterTag = function( title, dataAttr ) {
var html = '';
html += '' + title + ' ';
html += '';
html += '';
filter.container.find('.filter-tags-container .tags').append(html);
filter.refreshTagsEvent();
filter.filterProducts();
};
/**
* The method is adding `change` event for the check boxes.
*/
this.addCheckBoxEvent = function() {
var $checkBoxes = filter.container.find('.checkboxInput');
$checkBoxes.off('change').on('change', function() {
var $this = $(this);
if ( $this.is(':checked') ) {
filter.checkBoxCheckedEvent($this);
} else {
filter.checkBoxUnCheckedEvent($this);
}
});
}
/**
* The method is adding `change` event for the check boxes.
*/
this.addColorBoxEvent = function() {
var $colors = filter.container.find('.color');
$colors.off('click').on('click', function( event ) {
var $this = $(this);
if ( $this.hasClass('checked') ) {
$this.removeClass('checked');
var dataAttr = '.tag[data-unique-id="' + escapeHtml($this.data('unique-id')) + '"][data-type="color"][data-parent-unique-id="' + escapeHtml($this.data('parent-unique-id')) + '"]';
filter.container.find(dataAttr).remove();
filter.filterProducts();
} else {
$this.addClass('checked');
if ( filter.container.find('.filter-tags-container .tags .tag[data-unique-id="' + escapeHtml($this.data('unique-id')) + '"] ').length > 0 ) return;;
var dataAttr = 'data-unique-id="' + $this.data('unique-id') + '" data-type="color" data-parent-unique-id="' + escapeHtml($this.data('parent-unique-id')) + '"';
filter.addFilterTag($this.data('title'),dataAttr);
}
});
}
/**
* The method is refreshing the tags click events
* for example the remove of the tags.
*/
this.refreshTagsEvent = function() {
filter.container.find('.filter-tags-container .tags .close').off('click').on('click' ,function() {
var $tag = $(this).parent();
if ($tag.data('type') == 'color' ) {
filter.container.find('.color[data-unique-id="' + escapeHtml($tag.data('unique-id')) + '"]').removeClass('checked');
} else {
filter.container.find('.checkboxInput[value="' + escapeHtml($tag.data('unique-id')) + '"]').prop('checked',false);
}
$tag.remove();
filter.filterProducts();
});
};
/**
* The method is adding tags to the filter container
* of the checked check boxes.
* @param {object} $checkbox - Check box the user used.
*/
this.checkBoxCheckedEvent = function( $checkbox ) {
if ( filter.container.find('.filter-tags-container .tags .tag[data-unique-id="' + escapeHtml($checkbox.val()) + '"] ').length > 0 ) return;
var dataAttr = '';
dataAttr += 'data-unique-id="' + escapeHtml($checkbox.val()) + '" data-type="' + escapeHtml($checkbox.data('type')) + '" data-parent-unique-id="' + escapeHtml($checkbox.data('parent-unique-id')) + '"';
filter.addFilterTag($checkbox.data('title'),dataAttr);
};
/**
* The method is responsible for removing the
* tags from the filter container
*/
this.checkBoxUnCheckedEvent = function( $this ) {
var dataAttr = '';
dataAttr += '.tag[data-unique-id="' + escapeHtml($this.val()) + '"][data-type="' + escapeHtml($this.data('type')) + '"]';
filter.container.find(dataAttr).remove();
filter.refreshTagsEvent();
filter.filterProducts();
};
/**
* The method is filtering the product by the tags we have it the tags container.
*
* Note: Every tag has data attributes that
* the function is filtering by them.
*/
this.filterProducts = function() {
var $tags = filter.container.find('.filter-tags-container .tag');
if ( $tags.length == 0 ) filter.filteredProducts = false;
var dataAttr = '';
var products = Array();
filter.filterCombinations = {};
products = filter.filteredProducts;
/* If the user is filtering we will have tags that we need to find the
products who has their values */
if ( $tags.length > 0 ) {
$.each($tags, function( index, tag ) {
var $this = $(this);
switch ( $this.data('type') ) {
case 'price':
var obj = {};
obj.min = $this.data('min');
obj.max = $this.data('max');
filter.filterCombinations.price = {
min: obj.min,
max: obj.max
};
break;
default:
var obj = {};
obj.parentUniqueID = $this.data('parent-unique-id');
obj.val = $this.data('unique-id');
/* when the user is filtering for the second time we will have the filter combination json so we add there boxes objects that represents the boxes on the side menu of the filter */
if ( filter.filterCombinations[$this.data('type')] && filter.filterCombinations[$this.data('type')].boxes ) {
if ( filter.filterCombinations[$this.data('type')].boxes[obj.parentUniqueID] && filter.filterCombinations[$this.data('type')].boxes[obj.parentUniqueID].values ) {
filter.filterCombinations[$this.data('type')].boxes[obj.parentUniqueID].values.push(obj.val);
} else {
filter.filterCombinations[$this.data('type')].boxes[obj.parentUniqueID] = {
values: [obj.val]
};
}
} else {
var boxes = {};
boxes[obj.parentUniqueID] = {
values: [obj.val]
}
filter.filterCombinations[$this.data('type')] = {
boxes: boxes
};
}
break;
}
var searchIn = Array();
if ( $this.is(':first-child') ) {
searchIn = filter.products;
} else {
searchIn = products;
products = false;
}
var tmp = filter.getProductByFilterType($this.data('type'),obj,Array(),searchIn);
if ( products ) {
Array.prototype.push.apply(products,tmp);
} else {
products = tmp;
}
});
/* Save the result to the global parameter of the filter results because we have more methods who need
to have the filtered results */
filter.filteredProducts = products;
}
filter.resetProductsCounter();
$(filter.productsContainerSelector).fadeOut(200);
filter.getProductsByAjax();
};
/**
* The method is fetching the first page and reinitializing the infiniteScroll plugin by ruining a call back.
*/
this.getProductsByAjax = function() {
var $loader = $(filter.productsContainerSelector).parent().find('.s123-loader-ellips');
$loader.parent().show();
$loader.show();
/* destroy the `infiniteScroll` instance because we are now fetching the products with the filter
and after the ajax is returned we are reinitializing the `infiniteScroll` if we have more pages. */
if ( $(filter.productsContainerSelector).data('infiniteScroll') ) $(filter.productsContainerSelector).infiniteScroll('destroy');
$.ajax({
type: "GET",
url: '/versions/2/wizard/modules/eCommerceCollections/front/eCommerceFilterProducts.php',
data: {
w: filter.w,
websiteID: filter.websiteID,
filterCombinations: JSON.stringify(filter.filterCombinations),
pageNumber: 1,
type: filter.type,
uniquePageID: filter.uniquePageID,
eCommerceSearch: filter.eCommerceSearch
},
success: function( data ) {
data = tryParseJSON(data);
if ( !data ) return;
$(filter.productsContainerSelector).empty();
$(filter.productsContainerSelector).append(data.productsHtml);
eCommerceProductrBoxesEvents();
$(filter.productsContainerSelector).fadeIn(200, function() {
ActiveLazyImageLoad();
$('html').stop().animate({scrollTop: filter.$scrollTo.offset().top},600,function() {
if ( data.productsLeft > 0 ) {
InfiniteScroll_init(filter.type,filter.uniquePageID,JSON.stringify(filter.filterCombinations));
}
});
});
$loader.parent().hide();
$loader.hide();
}
});
};
/**
* The function is returning the products that contains
* option type and the value that the client selected.
*
* @param {string} type - Option Type (List,Color,Brand).
* @param {object} obj - Object that contains the values we compare with.
* @param {array} products - Array we fill with products.
* @return {array} products - All products that are matched.
*/
this.getProductByFilterType = function( type, obj, products, searchIn ) {
$.each(searchIn, function( key, product ) {
var allSettings = product.allSettings;
var productOptions = tryParseJSON(allSettings.productOptions);
var productAttributes = tryParseJSON(allSettings.productAttributes);
if ( productOptions.active && ['color','list','checkbox','radio','size'].indexOf(type) != -1 ) {
$.each(productOptions.options, function( key, po ) {
if ( po.type == type && type == 'color' ) {
$.each(po.items, function( key, item ) {
if ( obj.val == item.color && obj.parentUniqueID === po.id ) {
/**
* products is and array of all the products that the filter
* tool is showing to the user, we need to prevent a duplicated
* products in the array so before we add the product to the array
* we check if the product is already there.
*/
if ( !containsObject(product,products) ) {
products.push(product);
}
}
});
} else if ( po.type == type ) {
$.each(po.items, function( key, item ) {
if ( obj.val == item.id && obj.parentUniqueID === po.id ) {
/**
* products is and array of all the products that the filter
* tool is showing to the user, we need to prevent a duplicated
* products in the array so before we add the product to the array
* we check if the product is already there.
*/
if ( !containsObject(product,products) ) {
products.push(product);
}
}
});
}
});
}
if ( productAttributes.active && type == 'attribute' ) {
$.each(productAttributes.attributes, function( key, attr ) {
$.each(attr.values, function( key, value ) {
if ( obj.val == value.id && obj.parentUniqueID === attr.id ) {
/**
* products is and array of all the products that the filter
* tool is showing to the user, we need to prevent a duplicated
* products in the array so before we add the product to the array
* we check if the product is already there.
*/
if ( !containsObject(product,products) ) {
products.push(product);
}
}
});
});
}
if ( type == 'brand' ) {
var brand = allSettings[type];
if ( obj.val == brand ) {
/**
* products is and array of all the products that the filter
* tool is showing to the user, we need to prevent a duplicated
* products in the array so before we add the product to the array
* we check if the product is already there.
*/
if ( !containsObject(product,products) ) {
products.push(product);
}
}
}
if ( type == 'ribbon' ) {
var ribbon = allSettings[type];
if ( obj.val == ribbon ) {
/**
* products is and array of all the products that the filter
* tool is showing to the user, we need to prevent a duplicated
* products in the array so before we add the product to the array
* we check if the product is already there.
*/
if ( !containsObject(product,products) ) {
products.push(product);
}
}
}
if ( type == 'price' ) {
var price = parseFloat(allSettings.price);
if ( allSettings.onSale === 'on' && $.isNumeric(allSettings.salePrice) ) {
price = parseFloat(allSettings.salePrice);
}
if ( price >= obj.min && price <= obj.max ) {
/**
* products is and array of all the products that the filter
* tool is showing to the user, we need to prevent a duplicated
* products in the array so before we add the product to the array
* we check if the product is already there.
*/
if ( !containsObject(product,products) ) {
products.push(product);
}
}
}
});
return products;
};
/**
* The method is responsible for generating the filter box template
*/
this.getFilterBoxTemplate = function() {
var html = '';
html = '
';
html += '';
html += '{{title}}';
html += '';
html += '';
html += '
';
html += '{{content}}';
html += '
';
html += '
';
return html;
};
/**
* The method is responsible for the expand icon click event (show or hide the filter box ).
*/
this.addExpandBoxEvent = function() {
filter.container.find('.filter-type-title').on('click', function() {
filter.closeOpenBox($(this).find('.expand-filter'),200);
});
};
/**
* The method is responsible for the expand event (show or hide the filter box ).
* this method is called manually or called from click event of the box titles.
*
* @param {Jquery object} $expandIcon - The icon that the user has clicked on.
* @param {Integer} animationTime - Slide down and up animation time.
*/
this.closeOpenBox = function( $expandIcon, animationTime ) {
var $box = $expandIcon.closest('.filter-options').find('.filter-option-content');
if ( $box.hasClass('expanded') ) {
$expandIcon.removeClass('fa-minus').addClass('fa-plus');
$box.slideUp(animationTime,function() {
$box.removeClass('expanded');
filter.saveBoxesStateToCookie();
});
} else {
$expandIcon.removeClass('fa-plus').addClass('fa-minus');
$box.slideDown(animationTime,function() {
$box.addClass('expanded');
filter.saveBoxesStateToCookie();
});
}
};
/**
* The function is checking if the array already has
* the object and returns true if it has.
*
* Note: We use this to prevent duplicated products in
* array.
*
* Solution link: https://stackoverflow.com/a/4587130
*/
function containsObject( obj, list ) {
var x;
for (x in list) {
if (list.hasOwnProperty(x) && list[x] === obj) {
return true;
}
}
return false;
}
/**
* The function trying to parse the sent JSON string, we use it to prevent
* JS error if the JSON is not valid from some reason.
*
* @param {string} str - JSON string.
* @return {object} Obj - Valid Object or False if the sent JSON string is invalid.
*/
function tryParseJSON( str ) {
try {
var Obj = JSON.parse(str);
if ( Obj && typeof Obj === "object" ) {
return Obj;
}
} catch (e) {}
return false;
}
/**
* The function convert special characters to HTML entities, we use it when
* we add strings into HTML attributes, it used to prevent the breaks in
* the HTML e.g. title="abc"efg".
*
* Source: http://stackoverflow.com/questions/1787322/htmlspecialchars-equivalent-in-javascript
*/
function escapeHtml(text) {
if (!text) return text;
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
};
return text.toString().replace(/[&<>"']/g, function(m) {
return map[m];
});
}
};jQuery(function($) {
var rtl = $('html[dir=rtl]').length === 1;
var $section = $('section.s123-page-data-eCommerce');
var $mainImage = $section.find('.main-image > div');
var $productSlickcarousel = $section.find('#productSlickcarousel');
var $shareProductBtn = $section.find('.share-product-btn');
var storeLabels = tryParseJSON($('.store-labels').val());
var originalProductData = tryParseJSON($('.original-product-data').val());
var getShippingOnPageLoad = true;
$shareProductBtn.click(function() {
var $btn = $(this);
var url = $btn.data('url');
var title = decodeURIComponent($btn.data('title').replace(/\+/g, ' '));
var html = generateSharingPopoverHTML(title,url,title);
sharePopover($btn,html);
});
if ( $section.length === 0 ) return;
jQueryZoomInitialize($mainImage);
calculateMainImagesDimensionForMobile();
if ( $productSlickcarousel.length > 0 ) {
var verticalAlbum = $productSlickcarousel.parent().data('vertical-album') == 1 ? true : false;
/**
* Mobile Handler
*/
if ( isMobile.any() && whatScreen.any() === 'mobile' ) { // `whatScreen` used to prevent tablets
/**
* If the client is using a mobile device we need to change the
* variable `verticalAlbum` and the attribute `data-vertical-album` to 0
* because the style of the vertical album and the initialization of the
* album is also effected by this attribute.
*/
$productSlickcarousel.parent().attr('data-vertical-album',0);
verticalAlbum = false;
}
if ( !verticalAlbum ) {
$productSlickcarousel.width($section.find('.main-image').width());
}
/**
* Slick slider 1.8.1
* Documentation: http://kenwheeler.github.io/slick/
*/
$productSlickcarousel.slick({
dots: false,
infinite: true,
vertical: verticalAlbum,
verticalSwiping: verticalAlbum,
slidesToShow: 4,
slidesToScroll: 1,
adaptiveHeight: true,
rtl: verticalAlbum ? false : rtl,
arrows: true,
appendArrows: '.slick-list',
prevArrow: '
',
nextArrow: '
',
});
$productSlickcarousel.on('afterChange', function( event ) {
SlickCarouselClick($productSlickcarousel.find('.slick-current'));
});
$productSlickcarousel.find('.item').click(function() {
SlickCarouselClick($(this));
});
}
/**
* The function is responsible for converting the related products in to
* a horizontal slider by using the slick plugin.
*
* Note: The variable `slidesToShow` is determination how many images to show simultaneously in the slider.
* Mobile - Show only 1 images.
* Other devices - Show 4 images.
*/
(function() {
var $relatedProducts = $section.find('.related-products');
var $prevArrow = $('
');
var $nextArrow = $('
');
var slidesToShow = findBootstrapColPerRow($relatedProducts.children());
if ( $relatedProducts.children().length <= slidesToShow ) return;
$relatedProducts.parent().prepend($prevArrow);
$relatedProducts.parent().append($nextArrow);
$relatedProducts.parent().addClass('has-carousel');
/**
* Slick slider 1.8.1
* Documentation: http://kenwheeler.github.io/slick/
*/
$section.find('.related-products').slick({
dots: false,
infinite: true,
vertical: false,
verticalSwiping: false,
slidesToShow: slidesToShow,
slidesToScroll: 1,
adaptiveHeight: true,
rtl: rtl,
prevArrow: '.related-p-c-s-p',
nextArrow: '.related-p-c-s-n'
});
})();
/**
* The function is responsible for the carousel item click event, when
* the item is clicked we need to show the
*/
function SlickCarouselClick( $item ) {
$productSlickcarousel.find('.item').removeClass('slick-current');
$item.addClass('slick-current');
var $clickedImage = $item.find('.item-image');
var videoPath = '';
if ($clickedImage.data('media-type') == 'video') {
videoPath = $clickedImage.data('video-path');
}
jQueryZoomInitialize($clickedImage);
$mainImage.closest('.main-image').data('order',$clickedImage.data('order'));
$mainImage.css({
backgroundImage: $clickedImage.css('background-image')
});
}
/**
* The function initialize the jQuery Zoom Plugin on the main product image.
* Documentation: http://www.jacklmoore.com/zoom/
*
* @param {string} url - The URL of the image we like to zoom in to it.
*/
function jQueryZoomInitialize( $clickedImage ) {
if ( !$mainImage || $mainImage.length === 0 ) return;
if ( !$clickedImage || $clickedImage.length === 0 ) return;
if ($clickedImage.data('media-type') == 'video' ) {
$mainImage.empty();
$('').appendTo($mainImage);
} else {
$mainImage.empty();
var url = $clickedImage.data('zoom-image');
if ( isMobile.any() || $mainImage.closest('[data-enable-album-zoom="0"]').length > 0 ) return;
$mainImage.trigger('zoom.destroy');
/**
* It take some time for the zoom image to loaded and if the user hover the image
* before the zoom image finished loaded the zoom is not activate. We fix it by
* creating a div and removing it (for activate the `'mouseover' event).
*/
var loading = $('').appendTo($mainImage);
$mainImage.zoom({
url: url,
magnify: 1,
touch: true,
callback: function() {
loading.remove();
},
});
}
}
(function () {
var $productOptions = $section.find(".product-options");
var $options = $productOptions.find('.p-o-container');
if ( $productOptions.length !== 0 ) {
$options.filter('[data-type="color"]').each( function() {
var $option = $(this);
var $colors = $option.find('.p-o-color');
$colors.click( function( event ) {
var $color = $(this);
var title = $color.attr('title');
if ( $color.hasClass('selected') && !$option.data('mandatory') == 1 ) {
$colors.filter('.selected').removeClass('selected');
title = '';
} else {
$colors.filter('.selected').removeClass('selected');
$color.addClass('selected');
}
$option.find('.p-o-item-value').html(fixQuotIssue(title));
update();
disableRelatedProductOptions($color.get(0).id)
/**
* When the color has an image we need to show it when
* clicking on it
*/
if ( $color.hasClass('selected') ) {
setMainProductImage($color.find('[data-zoom-image]'));
} else {
setMainProductImage(null);
}
});
selectDefaultItem($option);
/**
* Update the product main image by fetching the image from
* the default item.
*/
var $defItem = $option.find('.selected [data-zoom-image]');
if ( $defItem.data('zoom-image') ) {
setMainProductImage($defItem);
}
});
$options.filter('[data-type="radio"]').each( function() {
var $option = $(this);
var $radios = $option.find('.p-o-radio');
$radios.click( function( event ) {
var $radio = $(this);
var title = $radio.attr('title');
if ( $radio.hasClass('selected') && !$option.data('mandatory') == 1 ) {
$radios.filter('.selected').removeClass('selected');
$radio.prop('checked',false);
title = '';
} else {
$radios.filter('.selected').removeClass('selected');
$radio.addClass('selected');
}
$option.find('.p-o-item-value').html(fixQuotIssue(title));
update();
/**
* When the color has an image we need to show it when
* clicking on it
*/
if ( $radio.hasClass('selected') ) {
setMainProductImage($radio);
} else {
setMainProductImage(null);
}
});
selectDefaultItem($option);
/**
* Update the product main image by fetching the image from
* the default item.
*/
var $defItem = $radios.filter('.selected');
if ( $defItem.data('zoom-image') ) {
setMainProductImage($defItem);
}
});
$options.filter('[data-type="checkbox"]').each( function() {
var $option = $(this);
var $checkboxes = $option.find('.p-o-checkbox');
$checkboxes.off('click').click( function( event ) {
var $checkbox = $(this);
$checkbox.hasClass('selected') ? $checkbox.removeClass('selected') : $checkbox.addClass('selected');
var itemValue = Array();
$checkboxes.filter('.selected').each(function() {
itemValue.push(fixQuotIssue($(this).attr('title')));
});
$option.find('.p-o-item-value').html(itemValue.join(','));
if ( $checkbox.is(':checked') ) {
setMainProductImage($checkbox);
} else {
setMainProductImage(null);
}
update();
});
selectDefaultItem($option);
/**
* Update the product main image by fetching the image from
* the default item.
*/
var $defItem = $checkboxes.filter('.selected');
if ( $defItem.data('zoom-image') ) {
setMainProductImage($defItem);
}
});
$options.filter('[data-type="size"]').each( function() {
var $option = $(this);
var $sizes = $option.find('.p-o-size');
$sizes.click( function( event ) {
var $size = $(this);
var title = $size.attr('title');
if ( $size.hasClass('selected') && !$option.data('mandatory') == 1 ) {
$sizes.filter('.selected').removeClass('selected');
title = '';
} else {
$sizes.filter('.selected').removeClass('selected');
$size.addClass('selected');
}
$option.find('.p-o-item-value').html(fixQuotIssue(title));
update();
disableRelatedProductOptions($size.get(0).id)
/**
* When the color has an image we need to show it when
* clicking on it
*/
if ( $size.hasClass('selected') ) {
setMainProductImage($size.find('[data-zoom-image]'));
} else {
setMainProductImage(null);
}
});
selectDefaultItem($option);
/**
* Update the product main image by fetching the image from
* the default item.
*/
var $defItem = $sizes.filter('.selected').find('[data-zoom-image]');
if ( $defItem.data('zoom-image') ) {
setMainProductImage($defItem);
}
});
$options.filter('[data-type="list"]').each( function() {
var $option = $(this);
var $list = $option.find('.p-o-list');
$list.change( function( event ) {
$list.find('option').removeClass('selected');
$list.find('option:selected').addClass('selected');
$option.find('.p-o-item-value').html(fixQuotIssue($list.val()));
update();
disableRelatedProductOptions($list.find('option:selected').get(0).id)
/**
* When the color has an image we need to show it when
* clicking on it
*/
setMainProductImage($list.find('option[value="'+$list.val()+'"]'));
});
selectDefaultItem($option);
/**
* Update the product main image by fetching the image from
* the default item.
*/
var $defItem = $list.find('.selected');
if ( $defItem.data('zoom-image') ) {
setMainProductImage($defItem);
}
});
$options.filter('[data-type="textArea"]').each( function() {
var $option = $(this);
var $textArea = $option.find('.p-o-textArea');
$textArea.on('input', function( event ) {
update();
});
});
$options.filter('[data-type="textField"]').each( function() {
var $option = $(this);
var $textField = $option.find('.p-o-textField');
$textField.on('input', function( event ) {
update();
});
});
$options.filter('[data-type="numbersField"]').each( function() {
var $option = $(this);
var $numbersField = $option.find('.p-o-numbersField');
$numbersField.on('input', function( event ) {
if ( !$.isNumeric($(this).val()) ) $(this).val($(this).val().replace(/[^0-9]/g,''));
update();
});
});
$options.filter('[data-type="datePicker"]').each( function() {
var $option = $(this);
var $datePicker = $option.find('.fake-input.p-o-datePicker');
var $hiddenInput = $option.find('[data-id="'+$datePicker.data('related-id')+'"]');
var calendar = new calendar_handler();
calendar.init({
$fakeInput: $datePicker,
$hiddenInput: $hiddenInput,
type: 'datePicker',
title: translations.chooseDate,
calendarSettings: {
format: $datePicker.data('date-format'),
weekStart: 0,
todayBtn: "linked",
clearBtn: false,
language: "en",
todayHighlight: true
},
onSubmit: function( selectedDate ) {
$datePicker.html(selectedDate);
$hiddenInput.val(selectedDate);
update();
}
});
});
$options.filter('[data-type="timePicker"]').each( function() {
var $option = $(this);
var $timePicker = $option.find('.fake-input.p-o-timePicker');
var $hiddenInput = $option.find('[data-id="'+$timePicker.data('related-id')+'"]');
var calendar = new calendar_handler();
calendar.init({
$fakeInput: $timePicker,
$hiddenInput: $hiddenInput,
type: 'timePicker',
title: translations.chooseTime,
onSubmit: function( selectedTime ) {
$timePicker.html(selectedTime);
$hiddenInput.val(selectedTime);
update();
}
});
});
$options.filter('[data-type="dateTimePicker"]').each( function() {
var $option = $(this);
var $dateTimePicker = $option.find('.fake-input.p-o-date-timePicker');
var $hiddenInput = $option.find('[data-id="'+$dateTimePicker.data('related-id')+'"]');
var calendar = new calendar_handler();
calendar.init({
$fakeInput: $dateTimePicker,
$hiddenInput: $hiddenInput,
type: 'dateTimePicker',
title: translations.chooseDateAndTime,
calendarSettings: {
format: $dateTimePicker.data('date-format'),
weekStart: 0,
todayBtn: "linked",
clearBtn: false,
language: "en",
todayHighlight: true
},
onSubmit: function( selectedDate, selectedTime ) {
$dateTimePicker.html(selectedDate + ' ' + selectedTime);
$hiddenInput.val(selectedDate + ' ' + selectedTime);
update();
}
});
});
$options.filter('[data-type="uploadFile"]').each( function() {
var $option = $(this);
var $uploadFile = $option.find('.p-o-uploadFile');
$uploadFile.on('change', function( event ) {
update();
});
});
update();
disableRelatedProductOptions(null, true);
updateProductOptionOnPageLoad();
}
/**
* The function update the product options object.
*/
function update() {
var po = [];
var totalItemsPrice = 0.00;
const productVariants = JSON.parse($('#productVariants').html());
var $productOptionsWithVariants = $options.filter(function() {
var $option = $(this);
var optionType = $option.data('type');
var noItemsOptionTypes = ['textArea', 'textField', 'numbersField', 'datePicker', 'timePicker', 'dateTimePicker', 'uploadFile', 'checkbox'];
return noItemsOptionTypes.indexOf(optionType) === -1;
}).sort(function(firstOption, secondOption) {
return $(firstOption).get(0).id.localeCompare($(secondOption).get(0).id);
});
$options.filter(function() {
var $option = $(this);
var optionType = $option.data('type');
var noItemsOptionTypes = ['textArea', 'textField', 'numbersField', 'datePicker', 'timePicker', 'dateTimePicker', 'uploadFile', 'checkbox'];
return noItemsOptionTypes.indexOf(optionType) !== -1;
}).each( function() {
var $option = $(this);
var pOption = new ProductOptions();
pOption.id = $option.get(0).id;
pOption.title = fixQuotIssue($option.data('title'));
pOption.type = $option.data('type');
switch( $option.data('type') ) {
case 'textField':
var $textField = $option.find('.p-o-textField');
if ( $textField.length === 0 ) return;
pOption.item.id = $textField.get(0).id;
pOption.item.value = fixQuotIssue($textField.val());
pOption.item.price = $textField.data('price');
totalItemsPrice += parseFloat(pOption.item.price);
po.push(pOption);
break;
case 'numbersField':
var $numbersField = $option.find('.p-o-numbersField');
if ( $numbersField.length === 0 ) return;
pOption.item.id = $numbersField.get(0).id;
pOption.item.value = fixQuotIssue($numbersField.val());
pOption.item.price = $numbersField.data('price');
totalItemsPrice += parseFloat(pOption.item.price);
po.push(pOption);
break;
case 'uploadFile':
var $uploadFile = $option.find('.p-o-uploadFile');
if ( $uploadFile.length === 0 || $uploadFile.val().length === 0 ) return;
pOption.item.id = $uploadFile.get(0).id;
pOption.item.value = fixQuotIssue($uploadFile.val());
pOption.item.price = $uploadFile.data('price');
totalItemsPrice += parseFloat(pOption.item.price);
po.push(pOption);
break;
case 'textArea':
var $textArea = $option.find('.p-o-textArea');
if ( $textArea.length === 0 ) return;
pOption.item.id = $textArea.get(0).id;
pOption.item.value = fixQuotIssue($textArea.val());
pOption.item.price = $textArea.data('price');
totalItemsPrice += parseFloat(pOption.item.price);
po.push(pOption);
break;
case 'datePicker':
var $datePicker = $option.find('.p-o-datePicker');
if ( $datePicker.length === 0 ) return;
pOption.item.id = $datePicker.get(0).id;
pOption.item.value = fixQuotIssue($option.find('[data-id="'+$datePicker.data('related-id')+'"]').val());
pOption.item.price = $datePicker.data('price');
totalItemsPrice += parseFloat(pOption.item.price);
po.push(pOption);
break;
case 'timePicker':
var $timePicker = $option.find('.p-o-timePicker');
if ( $timePicker.length === 0 ) return;
pOption.item.id = $timePicker.get(0).id;
pOption.item.value = fixQuotIssue($option.find('[data-id="'+$timePicker.data('related-id')+'"]').val());
pOption.item.price = $timePicker.data('price');
totalItemsPrice += parseFloat(pOption.item.price);
po.push(pOption);
break;
case 'dateTimePicker':
var $dateTimePicker = $option.find('.p-o-date-timePicker');
if ( $dateTimePicker.length === 0 ) return;
pOption.item.id = $dateTimePicker.get(0).id;
pOption.item.value = fixQuotIssue($option.find('[data-id="'+$dateTimePicker.data('related-id')+'"]').val());
pOption.item.price = $dateTimePicker.data('price');
totalItemsPrice += parseFloat(pOption.item.price);
po.push(pOption);
break;
case 'radio':
var $radio = $option.find('.p-o-radio.selected');
if ( $radio.length === 0 ) return;
pOption.item.id = $radio.get(0).id;
pOption.item.title = fixQuotIssue($radio.attr('title'));
pOption.item.price = $radio.data('price');
pOption.item.imgSrc = $radio.data('image-src');
totalItemsPrice += parseFloat(pOption.item.price);
po.push(pOption);
break;
case 'checkbox':
var $checkboxes = $option.find('.p-o-checkbox.selected');
/**
* In checboxes the logic is different
* so we need to make sure it will push all
* the selected checkboxes to the `po` array.
*/
$.each($checkboxes, function( index, checkbox ) {
pOption = new ProductOptions();
pOption.id = $option.get(0).id;
pOption.title = fixQuotIssue($option.data('title'));
pOption.type = $option.data('type');
pOption.item.id = $(this).get(0).id;
pOption.item.title = fixQuotIssue($(this).attr('title'));
pOption.item.price = $(this).data('price');
pOption.item.imgSrc = $(this).data('image-src');
po.push(pOption);
totalItemsPrice += parseFloat(pOption.item.price);
});
break;
}
});
$productOptionsWithVariants.each( function() {
var $option = $(this);
var pOption = new ProductOptions();
pOption.id = $option.get(0).id;
pOption.title = fixQuotIssue($option.data('title'));
pOption.type = $option.data('type');
pOption.required = $option.find('.p-o-required').length > 0;
switch( $option.data('type') ) {
case 'color':
var $color = $option.find('.p-o-color.selected');
if ( $color.length === 0 ) return;
pOption.item.id = $color.get(0).id;
pOption.item.title = fixQuotIssue($color.attr('title'));
pOption.item.price = $color.data('price');
pOption.item.imgSrc = $color.find('[data-zoom-image]').data('image-src');
totalItemsPrice += parseFloat(pOption.item.price);
po.push(pOption);
break;
case 'list':
var $list = $option.find('.p-o-list');
var $listSelectedOpt = $list.find('option:selected');
if ( $list.find('option').length === 0 || !$listSelectedOpt.get(0).id ) return;
pOption.item.id = $listSelectedOpt.get(0).id;
pOption.item.title = fixQuotIssue($list.val());
pOption.item.price = $listSelectedOpt.data('price');
pOption.item.imgSrc = $listSelectedOpt.data('image-src');
totalItemsPrice += parseFloat(pOption.item.price);
po.push(pOption);
break;
case 'size':
var $size = $option.find('.p-o-size.selected');
if ( $size.length === 0 ) return;
pOption.item.id = $size.get(0).id;
pOption.item.title = fixQuotIssue($size.attr('title'));
pOption.item.price = $size.data('price');
pOption.item.imgSrc = $size.find('[data-zoom-image]').data('image-src');
totalItemsPrice += parseFloat(pOption.item.price);
po.push(pOption);
break;
case 'radio':
var $radio = $option.find('.p-o-radio.selected');
if ( $radio.length === 0 ) return;
pOption.item.id = $radio.get(0).id;
pOption.item.title = fixQuotIssue($radio.attr('title'));
pOption.item.price = $radio.data('price');
pOption.item.imgSrc = $radio.find('[data-zoom-image]').data('image-src');
totalItemsPrice += parseFloat(pOption.item.price);
po.push(pOption);
break;
}
});
const productOptions = {
'options': po,
'variant': {}
}
if (productVariants.active) {
productOptions.variant = updateVariants(po);
} else {
addItemsPrice(totalItemsPrice)
}
$('#productOptions').html(JSON.stringify(productOptions));
$productOptions.trigger('po.update');
}
/**
* @description
* @param {any} optionId - the clicked option's id
* @return {void}
*/
function disableRelatedProductOptions(optionId, onPageLoad) {
resetDisableProductOptionsVariants();
const productVariants = JSON.parse($('#productVariants').html());
if(productVariants.active) {
for (let index = 0; index < productVariants.items.length; index++) {
const variant = productVariants.items[index];
const variantsOptionsId = splitVariantOptionsId(variant.optionsId);
if(optionId) {
const indexOfOptionId = variantsOptionsId.indexOf(optionId);
if(indexOfOptionId !== -1) {
if(!isVariantInStock(variant)) {
variantsOptionsId.splice(indexOfOptionId, 1);
disableProductOptionsVariants(variantsOptionsId, 'out of stock');
}
}
}
if(onPageLoad) {
if(!variant.active) {
disableProductOptionsVariants(variantsOptionsId);
}
}
}
}
}
function updateVariants(selectedOptions) {
const productVariants = JSON.parse($('#productVariants').html());
var optionsIds = [];
selectedOptions.forEach(function(option) {
if (['textArea','textField','numbersField','datePicker','timePicker','dateTimePicker','uploadFile', 'checkbox'].indexOf(option.type) != -1 ) return;
if (!option.required) return;
optionsIds.push(option.item.id);
});
if(optionsIds.length < 1) return {};
var optionsId = optionsIds.join('-');
if(optionsId.length === 0) return {};
let filteredVariants = productVariants.items.filter(function(variant) { return variant.optionsId === optionsId });
if(filteredVariants.length === 0) return {};
const selectedVariant = filteredVariants[0];
if(selectedVariant && !$.isNumeric(selectedVariant.inventory)) {
const inStock = selectedVariant.inventory === 'in stock' ? true : false;
if(!inStock || !selectedVariant.active) {
setProductOutOfStock(optionsIds);
} else {
setProductInStock();
}
} else {
setQuantityMax(selectedVariant, optionsIds);
}
if(selectedVariant && selectedVariant.sku) {
setProductSku(selectedVariant.sku);
} else {
setProductSku();
}
var price = addItemsPrice(selectedVariant.charge);
var newWeightAndPrice = getWeightAndPrice(price,selectedVariant.weight);
getShippingOnPageLoad = false;
getShippingInfo(newWeightAndPrice.price,newWeightAndPrice.weight);
return selectedVariant;
}
/**
* The function is returning the product weight and price.
*
* @param {integer} price - Price after the variants calculation.
* @param {integer} weight - Weight variants weight.
* @return {object} Object - price + weight.
*/
function getWeightAndPrice( price, weight ) {
originalProductData.weight = $.isNumeric(originalProductData.weight) ? originalProductData.weight : 0;
weight = $.isNumeric(weight) ? weight : 0;
return {
price: price,
weight: parseFloat(weight) + parseFloat(originalProductData.weight)
};
}
function updateProductOptionOnPageLoad() {
const productOptions = JSON.parse($('#productOptions').html());
const productVariants = JSON.parse($('#productVariants').html());
const variant = productOptions.variant;
if(Object.keys(variant).length === 0) return;
if($.isNumeric(variant.inventory)) {
if (variant.inventory > 0 && productVariants.active) return;
} else {
if (variant.inventory === 'in stock' && productVariants.active) return;
}
const otherVariants = productVariants.items
.filter(function(productVariant) {
return productVariant.optionsId !== variant.optionsId;
});
otherVariants.map(function(variant) {
if($.isNumeric(variant.inventory)) {
if(variant.inventory === 0) return;
} else {
if(variant.inventory === 'out of stock') return;
}
const variantOptionsId = splitVariantOptionsId(variant.optionsId)
variantOptionsId.forEach(function(optionsId) {
disableRelatedProductOptions(optionsId, true);
$options.each(function() {
const $option = $(this);
switch( $option.data('type') ) {
case 'color':
const $colors = $option.find('.p-o-color');
const $color = $option.find('.p-o-color#' + optionsId);
if($color.length !== 0) {
$colors.filter('.selected').removeClass('selected');
$color.addClass('selected');
$color.trigger('click');
$option.find('.p-o-item-value').html(fixQuotIssue($color.attr('title')));
}
break;
case 'radio':
const $radios = $option.find('.p-o-radio');
const $radio = $option.find('.p-o-radio#' + optionsId);
if($radio.length !== 0) {
$radios.filter('.selected').removeClass('selected');
$radio.addClass('selected');
$option.find('.p-o-item-value').html(fixQuotIssue($radio.attr('title')));
}
break;
case 'checkbox':
const $checkboxes = $option.find('.p-o-checkbox');
const $checkbox = $option.find('.p-o-checkbox#' + optionsId);
if($checkbox.length !== 0) {
$checkboxes.filter('.selected').removeClass('selected');
$checkbox.addClass('selected');
$option.find('.p-o-item-value').html(fixQuotIssue($checkbox.attr('title')));
}
break;
case 'size':
const $size = $option.find('.p-o-size#' + optionsId);
if ( $size.length !== 0 ) {
$size.attr('selected', true);
$size.trigger('click');
$option.find('.p-o-item-value').html(fixQuotIssue($size.attr('title')));
}
break;
case 'list':
const $list = $option.find('.p-o-list');
const $listSelectedOpt = $list.find('option#' + optionsId);
if ( $listSelectedOpt.length !== 0 ) {
$listSelectedOpt.attr('selected', true);
$listSelectedOpt.trigger('change');
$option.find('.p-o-item-value').html(fixQuotIssue($listSelectedOpt.val()));
}
break;
}
});
});
update();
});
}
function splitVariantOptionsId(optionsId) {
return optionsId.split('-')
.filter(function(v) {
return v !== 'poi';
}).map(function(id) {
return 'poi-' + id;
});
}
function setProductSku(value) {
if(!value) {
value = $section.find('#productSku').data('sku');
}
$section.find('#productSku').html(value);
}
function setQuantityMax(selectedVariant, optionsIds) {
const quantity = selectedVariant.inventory;
if(quantity > 0) {
if($('.quantity_field').val() > quantity) {
$('.quantity_field').val(quantity);
}
$('.quantity_field').attr('max', quantity);
if(!selectedVariant.active) {
setProductOutOfStock(optionsIds);
} else {
setProductInStock(optionsIds);
}
} else {
setProductOutOfStock(optionsIds);
$('.quantity_field').attr('max', 1);
}
}
function setProductOutOfStock(optionsIds) {
const $orderButtonPopup = $section.find(".orderButtonPopup");
if( $('.product-sale-banner').length !== 0 ) $('.product-sale-banner').hide();
if($('.product-out-of-stock').length === 0) {
$('.main-image').prepend('' + storeLabels.outOfStock + '');
}
$orderButtonPopup.attr('disabled', true);
$orderButtonPopup.text(storeLabels.outOfStock);
}
function setProductInStock(optionsIds) {
if( $('.product-sale-banner').length !== 0 ) $('.product-sale-banner').show();
const $orderButtonPopup = $section.find(".orderButtonPopup");
if($('.product-out-of-stock').length !== 0) {
$('.product-out-of-stock').remove();
}
$orderButtonPopup.attr('disabled', false);
$orderButtonPopup.text(storeLabels.addToCart);
}
/**
* @description Disables the product options if variant is out of stock
* @param {any} productOptionsId
* @return {void}
*/
function disableProductOptionsVariants(productOptionsId, type) {
var className = type === 'out of stock' ? 'p-o-v-out-of-stock' : 'p-o-v-hidden'
for (let index = 0; index < productOptionsId.length; index++) {
const optionId = productOptionsId[index];
$options.find('#' + optionId).addClass(className);
}
}
/**
* @description Enables the product options if variant is in stock and was disabled
* This is mainly effective on page load
* @param {any} productOptionsId
* @return {void}
*/
function resetDisableProductOptionsVariants() {
$options.each(function() {
$option = $(this);
$option.find('.p-o-v-out-of-stock').removeClass('p-o-v-out-of-stock');
})
}
function isVariantInStock(variant) {
if(variant && !$.isNumeric(variant.inventory)) {
const inStock = variant.inventory === 'in stock' ? true : false;
return inStock;
} else {
if(!variant.active || variant.inventory <= 0) {
return false;
} else {
return true;
}
}
}
/**
* Product Option Class.
*/
function ProductOptions() {
return {
id: null,
title: null,
type: null,
item: {
id: null,
title: null,
price: 0,
imgSrc : ''
}
};
}
/**
* The function add product items price to the product price.
*
* @param {float} totalItemsPrice - The total items price.
*/
function addItemsPrice( totalItemsPrice ) {
var $productPrice = $section.find('#productPrice');
var $price = $productPrice.find('[data-type="price"]');
if ( !$.isNumeric(totalItemsPrice) ) return;
if ( parseFloat($productPrice.data('price') ) + parseFloat(totalItemsPrice) == parseFloat($price.html()) ) return;
var p = parseFloat($productPrice.data('price')) + parseFloat(totalItemsPrice);
$price.html(p.toFixed(2));
if ( $section.find('#priceBeforeSale').length !== 0 ) {
var $priceBeforeSale = $section.find('#priceBeforeSale');
var $price = $priceBeforeSale.find('[data-type="price"]');
var pbs = parseFloat($priceBeforeSale.data('price')) + parseFloat(totalItemsPrice);
$price.html(pbs.toFixed(2));
var psp = ((1-(parseFloat(p)/parseFloat(pbs)))*100).toFixed(2);
psp = Number(psp);
$('.price-sale-precentege').html('(-'+psp+'%)');
}
$('.product-details').data('product-price',p);
return p;
}
/**
* The function is responsible for updating the main
* product image on product option click or change event.
*
* @param {Object} $item - The product option item that was clicked.
*/
function setMainProductImage( $item ) {
/**
* Product Has No Album & Po Item has no image - We take the backup div of the and send it to the
* `jQueryZoomInitialize` then the zoom will be refreshed with the original main image.
*/
if ( $('#productSlickcarousel').length == 0 && (!$item || $item.length === 0 || !$item.data('zoom-image')) ) {
$item = $('.original-main-image');
/**
* Product With Album & Po Item has no image - We take the last selected slick item and send it to the
* `jQueryZoomInitialize` then the zoom will be refreshed with the original main image.
*/
} else if ( $('#productSlickcarousel').length > 0 && (!$item || $item.length === 0 || !$item.data('zoom-image')) ) {
$item = $('#productSlickcarousel .slick-current .item-image');
}
$('.main-image [data-zoom-image]').attr('style','background-image: url("' + $item.data('zoom-image') + '");');
jQueryZoomInitialize($item);
}
/**
* The function is responsible for selecting the default item that the user has set from
* the product options.
*
* @param {Object} $option - The option that we need to select the default item.
*/
function selectDefaultItem( $option ) {
if ( !$option.data('default-item') ) return;
var $defItem = $option.find('#'+$option.data('default-item'));
var title = $defItem.attr('title');
if ( $defItem.is('input[type="checkbox"]') || $defItem.is('input[type="radio"]') ) {
$defItem.prop('checked',true);
} else if ( $defItem.is('option') ) {
$defItem.prop('selected',true);
title = $defItem.val();
}
$defItem.addClass('selected');
$option.find('.p-o-item-value').html(fixQuotIssue(title));
}
})();
/**
* The function convert `"` to `"`, We use data attribute to to pass
* some of the fields with `htmlspecialchars()` on the server side to
* prevent HTML break with quot, the JS function `stringify` doesn't
* handle `"` chars so we fix it manually by replacing it to `"`.
* In the feature we need to stop passing the values using `data`.
*/
function fixQuotIssue( value ) {
if ( !value ) return value;
return value.toString().replace(/\"/g,'\"');
}
$('.quantity_field').on('input', function() {
var $this = $(this);
if ( $this.val().length > 0 && !$.isNumeric($this.val()) ) $this.val(1);
if ( !$.isNumeric($this.val()) ) $this.val($this.val().replace(/[^0-9]/g,''));
if ( $.isNumeric($this.val()) && $this.val() <= 0 ) $this.val(1);
if ( parseInt($this.val()) > parseInt($this.prop('max')) ) {
$this.val($this.prop('max'));
quantityPopover($this,translations.productQuntityLimit.replace('{{units_limitation}}',$this.prop('max')));
} else if ( parseInt($this.val()) < parseInt($this.prop('min')) ) {
$this.val($this.prop('min'));
quantityPopover($this,translations.productQuntityLimitMin.replace('{{units_limitation}}',$this.prop('min')));
}
$section.find('.btn-buy-now.orderButtonPopup').data('quantity-amount',$this.val());
});
$section.find('.quantity-plus-btn').off('click').on('click', function() {
updateQuantity($(this).closest('.quantity_container').find('.quantity_field'),'plus');
});
$section.find('.quantity-minus-btn').off('click').on('click', function() {
updateQuantity($(this).closest('.quantity_container').find('.quantity_field'),'minus');
});
/**
* The function show a popover with a message related to the quantity validations.
*/
function quantityPopover( $input, message ) {
$input.popover({
container: $section,
content: message,
trigger: 'manual',
template: '
',
placement: function(popover, input) {
return isMobile.any() ? 'auto' : 'bottom';
}
});
$input.popover('show');
clearTimeout($input.data('q-p-timeout'));
$input.data('q-p-timeout',setTimeout(function(){
$input.popover('destroy');
},3000));
}
/**
* The function update the quantity
*/
function updateQuantity( $input, operator ) {
/**
* When product is out of stock we need to ignore the click events by checking
* if the `quantity_container` has a data attribute.
*/
if ( $input.closest('.quantity_container').data('disabled') == '1' ) return;
var quantity = parseInt($input.val());
var maxQuantity = parseInt($input.attr('max'));
var minQuantity = parseInt($input.attr('min'));
if ( operator === 'plus' && (quantity + 1) > maxQuantity ) {
quantityPopover($input,translations.productQuntityLimit.replace('{{units_limitation}}',$input.prop('max')));
} else if ( operator === 'minus' && quantity !== 1 && (quantity - 1) < minQuantity ) {
quantityPopover($input,translations.productQuntityLimitMin.replace('{{units_limitation}}',$input.prop('min')));
}
if ( operator === 'minus' && quantity > minQuantity ) quantity = quantity - 1;
if ( operator === 'plus' && quantity < maxQuantity ) quantity = quantity + 1;
if ( !$.isNumeric(quantity) ) quantity = 1;
$section.find('.btn-buy-now.orderButtonPopup').data('quantity-amount',quantity);
$input.val(quantity);
}
/**
* Bought together plugin
*/
(function(){
function boughtTogetherPlugin() {
var bt = this;
/**
* Initialize the plugin
*/
this.init = function( settings ) {
bt.$container = settings.$container;
bt.currencySymbol = settings.currencySymbol;
bt.updatePackagePrice();
bt.addCheckboxEvent();
};
/**
* The method is responsible for generating
* the price json of the checked products and saving
* the json in the text area.
*/
this.addCheckboxEvent = function() {
var $btCheck = bt.$container.find('.b-t-check:checked');
$btCheck.on('click', function() {
var $this = $(this);
if ( $this.is(':checked') ) {
bt.$container.find('.b-t-product-box[data-unique-id="'+$this.val()+'"]').fadeIn();
bt.$container.find('.b-t-plus-box[data-unique-id="'+$this.val()+'"]').fadeIn();
} else {
bt.$container.find('.b-t-product-box[data-unique-id="'+$this.val()+'"]').fadeOut();
bt.$container.find('.b-t-plus-box[data-unique-id="'+$this.val()+'"]').fadeOut();
}
bt.updatePackagePrice();
});
};
/**
* The method is responsible for updating the
* json and the package price price for the
* user.
*/
this.updatePackagePrice = function() {
var $btCheck = bt.$container.find('.b-t-check:checked');
var $packagePrice = bt.$container.find('.package-price');
var price = 0;
var products = [];
$.each($btCheck, function( index, checkBox ) {
var $this = $(this);
price += parseFloat($this.data('price'));
products.push($this.val());
});
$packagePrice.data('price',price);
$packagePrice.html(bt.currencySymbol+price.toFixed(2));
bt.$container.find('.orderButtonPopup').data('multi-products',JSON.stringify(products));
};
}
var bt = new boughtTogetherPlugin();
bt.init({
$container : $section.find('.bought-together-plugin'),
currencySymbol: $section.find('.bought-together-plugin').find('.package-price').find('[data-type="symbol"]').html()
});
})();
(function productPageTabsInit() {
var $firstTab = $section.find('.product-page-tabs').children().first();
$firstTab.addClass('active');
$($firstTab.find('a').attr('href')).addClass('active in');
if ( $section.find('a[data-toggle="tab"]').length == 1 ) {
$firstTab.find('a').trigger('click');
}
})();
/**
* The function is responsible for adding the product page a shipping details
* with a popup of the additional informations about the shipping.
*/
function getShippingInfo( price, weight ) {
if ( $('#productShipping').length == 0 ) return;
var weightMeasurement = $('#productShipping').data('weight');
var lengthMeasurement = $('#productShipping').data('length');
/**
* The function is adding the `see more` link with the popup
* option to the page.
*
* @param {Object} shipping - The object that contains all of the product shipping data.
*/
function addPopUp( shipping ) {
var html = '';
html += '
';
html += '
';
html += '';
html += '
';
$.each(shipping.shipping.options, function( index, option ) {
html += '
';
html += '
';
html += '';
html += ' ';
if ( option.deliveryTime ) {
html += '' + shipping.productData.translations.deliveryTime + ' ' + escapeHtml(option.deliveryTime) + '';
}
if ( option.formattedRate ) {
html += ' ';
html += '' + shipping.productData.translations.estimatedPrice + ' ' + option.formattedRate + '';
}
html += '
';
html += '
';
});
if ( shipping.storePickup ) {
html += '
';
html += '
';
html += '';
html += '
';
if ( shipping.storePickup.deliveryTime ) {
html += '' + shipping.productData.translations.message + ' ' + escapeHtml(shipping.storePickup.deliveryTime) + '';
html += ' ';
}
html += '' + translations.address + ' ' + escapeHtml(shipping.storePickup.address) + '';
html += ' ';
html += '' + translations.city + ' ' + escapeHtml(shipping.storePickup.city) + '';
html += ' ';
html += '' + translations.state + ' ' + escapeHtml(shipping.storePickup.state) + '';
html += ' ';
html += '' + translations.zipCode + ' ' + escapeHtml(shipping.storePickup.zipCode) + '';
html += ' ';
html += '' + translations.country_v2 + ' ' + escapeHtml(shipping.storePickup.country) + '';
html += '
';
html += '
';
html += '' + translations.instructions + ' ' + escapeHtml(shipping.storePickup.instructions) + ' ';
html += '
';
html += '
';
html += '
';
}
if ( hasWeightAndDimensions(shipping.productData) ) {
html += '';
if ( shipping.productData.weight ) {
html += '
';
html += '' + shipping.productData.translations.weight + '';
html += shipping.productData.weight+' '+weightMeasurement+'';
html += '
';
}
if ( shipping.productData.length ) {
html += '
';
html += '' + shipping.productData.translations.length + '';
html += shipping.productData.length+' '+lengthMeasurement+'';
html += '
';
}
if ( shipping.productData.width ) {
html += '
';
html += '' + shipping.productData.translations.width + '';
html += shipping.productData.width+' '+lengthMeasurement+'';
html += '
';
}
if ( shipping.productData.height ) {
html += '
';
html += '' + shipping.productData.translations.height + '';
html += shipping.productData.height+' '+lengthMeasurement+'';
html += '
';
}
}
html += '
';
var $seeMore = $('' + shipping.productData.translations.seeMoreLink + ' ');
$seeMore.on('click', function() {
var $btn = $(this);
showMoreEvent($btn,html);
});
$('#productShipping').append($seeMore);
}
/**
* The function is checking if the product has weight and dimensions and return true or false.
*
* @param {Object} productData - The object that contains the product shipping data.
* @return {Boolean} true / false
*/
function hasWeightAndDimensions( productData ) {
if ( productData.weight || productData.length || productData.width || productData.height ) return true;
return false;
}
/**
* The function is responsible for the `see more` click event, it is creating
* a popup that shows all additional information.
*
* @param {Object} $button - The button that need to show the popup.
* @param {String} html - Popup content.
*/
function showMoreEvent( $button, html ) {
var $html = $(html);
/**
* Bootstrap's Popovers Plugin Initial
* Documentation : http://getbootstrap.com/javascript/#popovers
*
* Important note: We append the popover to `product-container` instead of the body
* because we need the popover to inherit the sizes of it's parent
*/
$button.popover({
container: $('.product-container'),
html: 'true',
content: $html,
trigger: 'manual',
template: '
',
placement: function(popover, button) {
return !isMobile.any() ? 'auto' : 'top';
}
});
$button.popover('show');
$button.on('shown.bs.popover', function () {
$html.find('button').on('click', function(){
destroySharePopover();
});
$(document).on('mousedown.showMoreDestroyPopover', function ( event ) {
if ( $(event.target).closest('.popover.shipping-options').length === 0 ) {
destroySharePopover();
}
});
});
/**
* The function destroy the Popover and removes event handlers that were attached to it
*/
function destroySharePopover() {
$button.popover('destroy');
$(document).off('mousedown.showMoreDestroyPopover');
$(window).off('blur.showMoreDestroyPopover');
$(window).off('scroll.showMoreDestroyPopover');
}
}
/**
* The function is responsible for adding the product page a shipping information.
*/
(function addShippingInfoToPage() {
$.post('/versions/2/wizard/modules/eCommerce/getSingleProductShippingOptionsAjax.php', {
w : $('#w').val(),
websiteID : $('#websiteID').val(),
tranW : websiteLanguageCountryFullCode,
moduleID : 112,
uniqueID : $('#productShipping').data('unique-id'),
moduleTypeNUM : 112,
price : price,
weight : weight
}).done(function( shipping ) {
/* because we call this function every time that the variants will be changed
we need to make sure that the objects that contains the pop over ant the link will
be removed. */
$('#productShipping').find('.first-option').empty();
$('#productShipping').find('.see-more').remove();
shipping = tryParseJSON(shipping);
var html ='';
if ( !shipping.noShippingAvalible ) {
var firstOption = shipping.shipping.options[Object.keys(shipping.shipping.options)[0]];
var deliveryTime = escapeHtml(firstOption.deliveryTime) ? ' (' + escapeHtml(firstOption.deliveryTime) + ') ' : ' ';
var isFreeShipping = shipping.region.method === 'freeShipping';
var hasSeeMore = false;
delete shipping.shipping.options[Object.keys(shipping.shipping.options)[0]];
if ( isFreeShipping ) {
$('#productShipping').find('.first-option').addClass('free-shipping');
firstOption.formattedRate = '';
}
html = escapeHtml(firstOption.title) + deliveryTime + firstOption.formattedRate + ' ';
if ( Object.keys(shipping.shipping.options).length > 0 ) hasSeeMore = true;
if ( hasWeightAndDimensions(shipping.productData) ) hasSeeMore = true;
if ( hasSeeMore ) {
addPopUp(shipping);
}
} else {
html += shipping.message;
$('#productShipping').find('.first-option').addClass('no-shipping');
}
$('#productShipping').find('.first-option').append(html);
});
})();
}
/**
* Get Shipping On Page Load - If the flag `getShippingOnPageLoad` is true we need to fetch
* the shipping with the default weight and price property of the product, otherwise this
* flag will be false because the variants also using the function `getShippingInfo`
* to show the user the shipping information of the product with the selected variants.
*/
if ( getShippingOnPageLoad ) {
getShippingInfo(originalProductData.price,originalProductData.weight);
}
/**
* The function is creating a `see more` link for the return policy text
*/
(function() {
if ( $('.product-return-policy[data-more="1"]').length == 0 ) return;
var html = '';
html += '
';
html += '';
html += $('.return-policy.original-text').val();
html += '
';
var $seeMore = $('' + translations.seeMore + '');
$seeMore.on('click', function() {
var $btn = $(this);
showMoreEvent($btn,html);
});
$('.product-return-policy[data-more="1"]').closest('li').append($seeMore);
/**
* The function is responsible for the `see more` click event, it is creating
* a popup that shows all additional information.
*
* @param {Object} $button - The button that need to show the popup.
* @param {String} html - Popup content.
*/
function showMoreEvent( $button, html ) {
var $html = $(html);
/**
* Bootstrap's Popovers Plugin Initial
* Documentation : http://getbootstrap.com/javascript/#popovers
*
* Important note: We append the popover to `product-container` instead of the body
* because we need the popover to inherit the sizes of it's parent
*/
$button.popover({
container: $('.product-container'),
html: 'true',
content: $html,
trigger: 'manual',
template: '
',
placement: function(popover, button) {
return !isMobile.any() ? 'auto' : 'top';
}
});
$button.popover('show');
$button.on('shown.bs.popover', function () {
$html.find('button').on('click', function(){
destroySharePopover();
});
$(document).on('mousedown.showMoreDestroyPopover', function ( event ) {
if ( $(event.target).closest('.popover.shipping-options').length === 0 ) {
destroySharePopover();
}
});
});
/**
* The function destroy the Popover and removes event handlers that were attached to it
*/
function destroySharePopover() {
$button.popover('destroy');
$(document).off('mousedown.showMoreDestroyPopover');
$(window).off('blur.showMoreDestroyPopover');
$(window).off('scroll.showMoreDestroyPopover');
}
}
})();
/**
* The function convert special characters to HTML entities, we use it when
* we add strings into HTML attributes, it used to prevent the breaks in
* the HTML e.g. title="abc"efg".
*
* Source: http://stackoverflow.com/questions/1787322/htmlspecialchars-equivalent-in-javascript
*/
function escapeHtml( text ) {
if ( !text ) return text;
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.toString().replace( /[&<>"']/g, function( m ) { return map[m]; } );
}
/**
* Product Gallery Initialize
*/
(function () {
var $mainImage = $('.main-image');
var productGallery = tryParseJSON($('#productGallery').val());
if ( $mainImage.length === 0 || !productGallery ) return;
$mainImage.on('click',function( event ) {
var $product_mfp_gallery = init();
$product_mfp_gallery.magnificPopup('open',$mainImage.data('order'));
});
/**
* The function initialize the product gallery object.
*/
function init() {
var $product_mfp_gallery = $('.product-mfp-gallery');
if ( $('.product-mfp-gallery').length !== 0 ) return $product_mfp_gallery;
$product_mfp_gallery = $('').appendTo('body');
$.each(productGallery, function( index, image ) {
$product_mfp_gallery.append('');
});
/**
* Magnific Popup Initial
* Documentation : http://dimsemenov.com/plugins/magnific-popup/documentation.html
*/
$product_mfp_gallery.magnificPopup({
mainClass: 'mfp-e-product-gallery',
delegate: '.e-p-mfp-image', // Categories Filter
closeOnContentClick: true,
closeBtnInside: false,
tLoading: translations.loading, // Text that is displayed during loading
gallery: {
enabled: true,
tClose: translations.closeEsc, // Alt text on close button
tPrev: translations.previousLeftArrowKey, // Alt text on left arrow
tNext: translations.NextRightArrowKey, // Alt text on right arrow
tCounter: '%curr% '+translations.of+' %total%' // Markup for "1 of 7" counter
},
image: {
markup: '
'+
''+
''+
'
'+
''+
''+
''+
'
'+
'
',
titleSrc: 'data-caption',
tError: translations.imageCouldNotLoaded // Error message when image could not be loaded
},
iframe: {
/**
* Magnific Popup doesn't show the caption on IFrames so we add it manually
* Source: https://stackoverflow.com/a/22023434/469161
*/
markup: '
' +
'' +
'' +
'' +
'
',
patterns: {
site123: {
index: $GLOBALS['cdn-user-files'],
id: function( url ) {
/**
* Mobile Handler - The auto-play is not working at mobile
* if the video is not muted, so we disable it.
*/
if ( isMobile.any() ) url += '&autoplay=0';
return url;
},
src: '/include/globalVideoPlayer.php?cad=1&url=%id%'
},
site123Processing: {
index: '/files/images/video-processing.png',
id: function( url ) {
/**
* Mobile Handler - The auto-play is not working at mobile
* if the video is not muted, so we disable it.
*/
if ( isMobile.any() ) url += '&autoplay=0';
return url;
},
src: '/include/globalVideoPlayer.php?cad=1&url=%id%'
}
}
},
callbacks: {
elementParse: function( item ) {
if( item.el.data('type') === 'video' ) {
item.type = 'iframe';
} else {
item.type = 'image';
}
}
}
});
return $product_mfp_gallery;
};
})();
/**
* Mobile Only - The function is calculate the images dimension related to the selected ratio and overwriting
* the width and height with the result.
*
* Note: Because of the technology limitation on server side we couldn't calculate the screen size of the user
* and the `div` tag size that is using the image as background image so we are using javascript instead,
* the PC version is calculated from the server side.
*/
function calculateMainImagesDimensionForMobile() {
if ( $mainImage.length === 0 || !isMobile.any() || whatScreen.any() !== 'mobile' ) return;
var ratio = $section.find('.main-image').data('ratio');
var split_ratio = ratio.split('-');
var ratio_width = split_ratio[0];
var ratio_height = split_ratio[1];
var aspect_ratio = parseFloat(ratio_height) / parseFloat(ratio_width);
var width = screen.width - 30;
var height = (parseFloat(width) * parseFloat(aspect_ratio)).toFixed(2);
$section.find('.main-image').css({
width: width,
height: height,
});
}
/**
* Reviews handler - Initialize the review tool
*/
(function() {
var Review = new Comments_Initialize({
id: 'productPageReview',
type: 1,
onLoad: function( reviews, reviewAvg, newReview ) {
if ( reviews == 0 ) {
Review_DataPage.hideReview();
} else {
Review_DataPage.showReview();
}
Review_DataPage.addReviewAvgToPage(reviewAvg,reviews);
if ( newReview ) {
var $newReview = $('#commentsContainer .commentBox[data-comment-id="'+Review_DataPage.newReviewID+'"]');
if ( $newReview.length > 0 ) {
Review_DataPage.focusUserOnNewReview();
}
}
},
onFormSubmit: function( newReviewID, blockComment ) {
if ( blockComment ) {
Review_DataPage.showManagerApproveMessage();
Review_DataPage.newReviewID = null;
} else {
Review_DataPage.newReviewID = newReviewID;
Review_DataPage.hideModal();
}
}
});
var Review_DataPage = function() {
var that = this;
/**
* The method is initializing the review data page object.
*/
that.init = function() {
that.$reviewTabLink = $('#reviewsTabLink');
that.$reviewTabContent = $('#reviews');
that.$form = $('#productPageReview .commentsForm');
that.newReviewID = null;
if ( that.$form.length === 0 ) return;
that.$modal = $('
'+translations.productReviewMessage+'
');
that.$modal.find('.bootbox-body #reviewFormContainer').append(that.$form);
$('body').append(that.$modal);
that.$addNewReview = $section.find('.addNewReview');
that.$addNewReview.on('click', function() {
that.$modal.modal('show');
that.showReviewForm();
});
/* add the review loading icon to the page title*/
var html = '';
html += '
';
html += '';
html += '
';
$section.find('.review-container').prepend(html);
};
/**
* The method is responsible for adding the review sum of the page to the page title.
*
* @param {float} reviewAvg - Review average
* @param {int} reviews - The reviews amount
*/
that.addReviewAvgToPage = function( reviewAvg, reviews ) {
var $reviewContainer = $section.find('.review-container');
that.generateStarsHtml(reviewAvg);
$reviewContainer.find('.review-sum').html(that.generateStarsHtml(reviewAvg)+' ' + reviews + '');
$reviewContainer.find('.addNewReview').show();
};
/**
* The method is returning the review stars according to the review average
*
* Get the decimal first number after the dot - https://stackoverflow.com/a/4512328
*
* @param {float} reviewAvg - The average calculation of the reviews
*/
that.generateStarsHtml = function( reviewAvg ) {
var html = '';
var num = parseInt(reviewAvg);
var decimal = (reviewAvg - Math.floor(reviewAvg)) *10;
var addHalfStar = decimal > 0;
for ( var i = 1; i <= 5 ; i++ ) {
if ( i <= num ) {
html += '';
} else if ( i > num && addHalfStar ) {
html += '';
addHalfStar = false;
} else {
html += '';
}
html += ' ';
}
return html;
};
/**
* The method is responsible for hiding all what is related to the review.
*/
that.hideReview = function() {
var $tabsContainer = $section.find('.tabs-container');
var $tabLinks = $tabsContainer.find('.product-page-tabs');
var $tabs = $tabsContainer.find('.tab-content');
$tabs.find('#reviews').addClass('hidden');
$tabLinks.find('#reviewsTabLink').parent().addClass('hidden');
$tabLinks.children(':not(.hidden)').first().find('a').trigger('click');
if ( !$section.find('.product-page-tabs').children().is(':visible') ) $tabsContainer.addClass('hidden');
};
/**
* The method is responsible for showing all what is related to the review.
*/
that.showReview = function() {
var $tabsContainer = $section.find('.tabs-container');
var $tabLinks = $tabsContainer.find('.product-page-tabs');
var $tabs = $tabsContainer.find('.tab-content');
$tabs.find('#reviews').removeClass('hidden');
$tabLinks.find('#reviewsTabLink').parent().removeClass('hidden');
/* when the product have only review feature and no reviews we were hiding the `more-info strip` and now when
the product have reviews we need to shwo again the `more-info strip` */
$tabsContainer.removeClass('hidden');
};
/**
* The method is responsible for hiding the review modal
*/
that.hideModal = function() {
if ( !that.$modal ) return;
that.$modal.modal('hide');
};
/**
* The method is responsible for showing the message that his review will be approved
* by the website manager because the global setting `auto confirm` is off
*/
that.showManagerApproveMessage = function() {
that.$modal.find('#reviewFormContainer').fadeOut(function() {
that.$modal.find('#reviewAutoConfirmMsg').fadeIn();
});
};
/**
* The method is responsible for showing the review form and hiding the website manager auto
* confirm message, we call this method every time that the modal is opened because we need to make sure
* that the form is shown.
*/
that.showReviewForm = function() {
that.$modal.find('#reviewAutoConfirmMsg').hide();
that.$modal.find('#reviewFormContainer').show();
};
/**
* The method is responsible to focus the user on the new review by scrolling
* down to the new review that he added
*/
that.focusUserOnNewReview = function() {
if ( that.$reviewTabContent.is(':visible') ) {
scrollToReview();
} else {
that.$reviewTabLink.one('shown.bs.tab', function() {
scrollToReview();
}).trigger('click');
}
/**
* The function is scrolling to the new review that the user recently added
*/
function scrollToReview() {
/* some layouts has some padding that we need to scroll up to it,
on mobile it will be always 60 because we have the same layout*/
var offset = findBootstrapEnvironment() != 'xs' ? menuScrollOffset : menuScrollOffset_mobile;
$('html, body').stop().animate({
scrollTop: ($('#commentsContainer .commentBox[data-comment-id="'+that.newReviewID+'"]').offset().top - offset)
},600);
}
};
return that;
}();
Review_DataPage.init();
})();
});$( document ).on( "s123.page.ready", function( event ) {
var rtl = $('html[dir=rtl]').length === 1;
eCommerceProductBoxCarousel_init();
/**
* Initialize the filter tool object - Get filter tool json and add it additional parameters such as
* container, productsSelector, productsContainerSelector for the filter
* tool js file.
*/
eCommerceFilterTool.init(tryParseJSON($('.filter-object-data').val()));
InfiniteScroll_init($('[data-s123-pagination="true"]').data('type'),$('[data-s123-pagination="true"]').data('unique-page-id'),'');
/**
* Initialize the collections menu construction on page load.
*/
(function() {
/**
* The function is responsible for creating a nodes tree for the
* collections menu by calling it self.
*
* @param {object} $collections - The collections we need to generate for them nodes.
* @param {object} parentState - The original state of the parent, that we need to preserve.
* @return {object} obj - The nodes result that we generated.
*/
function getCategoriesTree( $collections, parentState ) {
/**
* this object will be returned the the parent that called
* the function `getCategoriesTree` and the parent will get
* the state inside the object.
*
* Note: In order to keep the parent expanded so the user will
* see all the children we need those parameters.
*/
var obj = {
parent: {
state: parentState
},
nodes: []
}
/**
* loop over the collections and get their children + update
* the current collection state.
*/
$.each($collections, function( index, collection ) {
var $collection = $(collection);
/**
* if the collections is active we need to keep the
* parent expanded and un mark the parent from active.
*/
if ( $collection.data('active') == '1' ) {
obj.parent.state.expanded = true;
obj.parent.state.selected = false;
}
var collectionObj = {
text: $collection.data('title'),
href: $collection.data('href'),
state: {
selected: $collection.data('active') == '1',
expanded: $collection.data('active') == '1'
},
nodes: []
}
var $children = $collection.children().filter('.sub-collections').find('ul').first().children();
/**
* if the collection has children we need to create for them nodes
* and also show all the selected collection path
*/
if ( $children.length > 0 ) {
var tree = getCategoriesTree($children,collectionObj.state);
collectionObj.nodes = tree.nodes;
collectionObj.state = tree.parent.state;
if ( tree.parent.state.expanded ) obj.parent.state.expanded = true;
/**
* in order to remove expand icon if the collection
* has no children we delete the index `nodes`.
*/
} else {
delete collectionObj.nodes;
}
obj.nodes.push(collectionObj);
});
return obj;
}
var tree = [];
var defState = {
selected: false,
expanded: false
}
/**
* At the moment we show all of the sub collections without the root collection, if we want to show the root
* collections we need to replace the the code with
* `var categoriesNodes = getCategoriesTree($('.collections-container.nav').children(),defState).nodes`
*/
var categoriesNodes = getCategoriesTree($('.collections-container.nav .sub-collections ul').first().children(),defState).nodes;
/**
* Get all root nodes only from the `categoriesNodes` and save them inside
* the tree array.
*/
$.each(categoriesNodes, function( index, collection ) {
tree.push(collection);
});
/**
* Bootstrap Treeview Initialize
* https://github.com/jonmiles/bootstrap-treeview
*/
$('.collections-container.nav').treeview({
data: tree,
levels: 3,
expandIcon: 'fa fa-plus',
collapseIcon: 'fa fa-minus',
showBorder: false,
backColor: '#428bca00',
color: '#428bca',
selectedColor: '#428bca',
selectedBackColor: '#428bca00',
highlightSelected: true,
enableLinks: true,
onNodeSelected: function(event, data) {
window.location = data.href;
}
})
.show();
})();
/**
* The function is responsible for converting the homepage sections items in to
* a horizontal slider by using the slick plugin.
*
* Note: The variable `slidesToShow` is determination how many images to show simultaneously in the slider.
* Mobile - Show only 1 images.
* Other devices - Show 4 images.
*/
(function() {
var $homepageSections = $('#section-112 .homepage-section');
$.each($homepageSections, function( index, section ) {
var $sectionItemsContainer = $(section).find('.e-commerce-items');
var sectionData = tryParseJSON($(section).find('.section-data').val());
var sectionID = sectionData.id;
var sectionStyle = sectionData.style;
if ( sectionStyle == 2 ) carousel_init();
/**
* The function initialize the carousel.
*/
function carousel_init() {
var $prevArrow = $('
');
var $nextArrow = $('
');
/*
* Carousel Handler - We don't like that the users will see the carousel rendering
* so we hide the products and display them after render finished. e.g. if we don't
* hide them the user will see all the products on page load and then it will replace
* to be carousel.
* Note: We also must do that before we set `slidesToShow` because it will get a wrong
* calculations if the products are hidden.
*/
$sectionItemsContainer.css({ display: 'flex' });
var slidesToShow = findBootstrapColPerRow($sectionItemsContainer.children());
if ( $sectionItemsContainer.children().length <= slidesToShow ) return;
$sectionItemsContainer.parent().prepend($prevArrow);
$sectionItemsContainer.parent().append($nextArrow);
$sectionItemsContainer.parent().addClass('homepage-section-container');
/**
* Slick slider 1.8.1
* Documentation: http://kenwheeler.github.io/slick/
*/
$sectionItemsContainer.slick({
dots: false,
infinite: true,
vertical: false,
verticalSwiping: false,
slidesToShow: slidesToShow,
slidesToScroll: 1,
adaptiveHeight: true,
swipeToSlide: true,
rtl: rtl,
prevArrow: '.related-p-c-s-p[data-section-id="'+sectionID+'"]',
nextArrow: '.related-p-c-s-n[data-section-id="'+sectionID+'"]'
});
}
});
})();
/**
* E-commerce Search Page Empty Value Bug Fix - When the search input had no value the search page
* redirected the user to the homepage so we decided for now to prevent the enter key event on the
* search input when the value is empty
*/
$('.search-result-page-e-commerce #eCommerceSearch').keydown( function( event ) {
if ( event.which === 13 && $(this).val().length === 0 ) event.preventDefault();
});
});
/**
* The function is refreshing all of the product boxes events by triggering different
* page ready events of the system, we user this function after we append the product boxes
* to the page
*/
function eCommerceProductrBoxesEvents() {
$(document).trigger('s123.page.ready.data-model');
$(document).trigger('s123.page.ready.activeOrderPopup');
$(document).trigger('s123.page.ready.wish_list');
eCommerceProductBoxCarousel_init();
}
/**
* The function is initializing the `infiniteScroll` plugin
*/
function InfiniteScroll_init( type, uniquePageID, filterCombinations ) {
var $container = $('[data-s123-pagination="true"]');
var $loadingIcon = $container.parent().children('.s123-page-load-status');
var paginationProductsLeft = $container.data('pagination-products-left');
if ( $container.length === 0 ) return;
if ( parseInt(paginationProductsLeft) === 0 ) return;
if ( $loadingIcon.length === 0 ) {
$container.parent().append('
');
}
/**
* InfiniteScroll Initialize
* Documentations: https://infinite-scroll.com/options.html
*/
$container.infiniteScroll({
append: false,
/* we set this property to `text` because some browsers like IE11 don't support the ability `XMLHttpRequest.responseType`
and as result the the infiniteScroll will not add the products to the page. */
responseType: 'text',
scrollThreshold: 400,
loadOnScroll: true,
history: false,
status: '.s123-page-load-status',
/* The method `path` is triggered when the `InfiniteScroll` is making a request for the next page and because our url parameters for path are dynamic we are using this function to generate a valid url for our needs */
path: function() {
/* load count is the variable that determinate how many times the `infiniteScroll` has fetched the next page but in our
case we need always to start from page 2 because the filter has it's own ajax that is fetching the page 1 */
if ( this.loadCount < 2 ) this.loadCount = 2;
var path = '/versions/2/wizard/modules/eCommerceCollections/front/eCommerceFilterProducts.php?w='+encodeURIComponent(w.value)+'&websiteID='+encodeURIComponent(websiteID.value)+'&pageNumber='+encodeURIComponent(this.loadCount)+'&filterCombinations='+encodeURIComponent(filterCombinations)+'&type='+encodeURIComponent(type)+'&uniquePageID='+encodeURIComponent(uniquePageID);
if ( $('#eCommerceSearch').length > 0 ) path += '&eCommerceSearch='+encodeURIComponent($('#eCommerceSearch').val());
return path;
}
})
.off('load.infiniteScroll').on('load.infiniteScroll', function( event, response ) {
response = tryParseJSON(response);
$container.infiniteScroll('appendItems',$(response.productsHtml));
eCommerceProductrBoxesEvents();
ActiveLazyImageLoad();
/* destroy the instance of the `infiniteScroll` because we have reached the last page and in order
to get the next page we plugin so no events will run any more
becuase we are re initilizing it every time */
if ( response.productsLeft == 0 ) $container.infiniteScroll('destroy');
});
}
/**
* The function is initializing the product boxes carousel
*/
function eCommerceProductBoxCarousel_init() {
var rtl = $('html[dir=rtl]').length === 1;
/**
* Query OwlCarousel2 Plugin Initial
* Documentation: https://owlcarousel2.github.io/OwlCarousel2/docs/started-welcome.html
*
* E-commerce products box carousel album initialize.
* This function is responsible for adding to the product box
* a an album carousel type.
*/
$('.s123-module-eCommerce').each(function() {
$(this).find('.product-box-carousel').each(function() {
var $product_box_carousel = $(this);
$product_box_carousel.owlCarousel({
items: 1,
center: true,
nav: true,
slideTransition: 'ease',
dots: false,
navSpeed: 500,
mouseDrag: false,
loop: true,
rtl :rtl,
navText: [
'',
''
],
});
$product_box_carousel.find('.owl-nav')
.off('click.owl_nav')
.on('click.owl_nav', function( event ) {
var $this = $(this);
var $target = $(event.target);
if ( $target.is($this) ) {
$product_box_carousel.find('.owl-item.active .product-image').get(0).click();
}
})
.css({ cursor: 'pointer' });
});
});
}!function(i){"use strict";"function"==typeof define&&define.amd?define(["jquery"],i):"undefined"!=typeof exports?module.exports=i(require("jquery")):i(jQuery)}(function(i){"use strict";var e=window.Slick||{};(e=function(){var e=0;return function(t,o){var s,n=this;n.defaults={accessibility:!0,adaptiveHeight:!1,appendArrows:i(t),appendDots:i(t),arrows:!0,asNavFor:null,prevArrow:'',nextArrow:'',autoplay:!1,autoplaySpeed:3e3,centerMode:!1,centerPadding:"50px",cssEase:"ease",customPaging:function(e,t){return i('').text(t+1)},dots:!1,dotsClass:"slick-dots",draggable:!0,easing:"linear",edgeFriction:.35,fade:!1,focusOnSelect:!1,focusOnChange:!1,infinite:!0,initialSlide:0,lazyLoad:"ondemand",mobileFirst:!1,pauseOnHover:!0,pauseOnFocus:!0,pauseOnDotsHover:!1,respondTo:"window",responsive:null,rows:1,rtl:!1,slide:"",slidesPerRow:1,slidesToShow:1,slidesToScroll:1,speed:500,swipe:!0,swipeToSlide:!1,touchMove:!0,touchThreshold:5,useCSS:!0,useTransform:!0,variableWidth:!1,vertical:!1,verticalSwiping:!1,waitForAnimate:!0,zIndex:1e3},n.initials={animating:!1,dragging:!1,autoPlayTimer:null,currentDirection:0,currentLeft:null,currentSlide:0,direction:1,$dots:null,listWidth:null,listHeight:null,loadIndex:0,$nextArrow:null,$prevArrow:null,scrolling:!1,slideCount:null,slideWidth:null,$slideTrack:null,$slides:null,sliding:!1,slideOffset:0,swipeLeft:null,swiping:!1,$list:null,touchObject:{},transformsEnabled:!1,unslicked:!1},i.extend(n,n.initials),n.activeBreakpoint=null,n.animType=null,n.animProp=null,n.breakpoints=[],n.breakpointSettings=[],n.cssTransitions=!1,n.focussed=!1,n.interrupted=!1,n.hidden="hidden",n.paused=!0,n.positionProp=null,n.respondTo=null,n.rowCount=1,n.shouldClick=!0,n.$slider=i(t),n.$slidesCache=null,n.transformType=null,n.transitionType=null,n.visibilityChange="visibilitychange",n.windowWidth=0,n.windowTimer=null,s=i(t).data("slick")||{},n.options=i.extend({},n.defaults,o,s),n.currentSlide=n.options.initialSlide,n.originalSettings=n.options,void 0!==document.mozHidden?(n.hidden="mozHidden",n.visibilityChange="mozvisibilitychange"):void 0!==document.webkitHidden&&(n.hidden="webkitHidden",n.visibilityChange="webkitvisibilitychange"),n.autoPlay=i.proxy(n.autoPlay,n),n.autoPlayClear=i.proxy(n.autoPlayClear,n),n.autoPlayIterator=i.proxy(n.autoPlayIterator,n),n.changeSlide=i.proxy(n.changeSlide,n),n.clickHandler=i.proxy(n.clickHandler,n),n.selectHandler=i.proxy(n.selectHandler,n),n.setPosition=i.proxy(n.setPosition,n),n.swipeHandler=i.proxy(n.swipeHandler,n),n.dragHandler=i.proxy(n.dragHandler,n),n.keyHandler=i.proxy(n.keyHandler,n),n.instanceUid=e++,n.htmlExpr=/^(?:\s*(<[\w\W]+>)[^>]*)$/,n.registerBreakpoints(),n.init(!0)}}()).prototype.activateADA=function(){this.$slideTrack.find(".slick-active").attr({"aria-hidden":"false"}).find("a, input, button, select").attr({tabindex:"0"})},e.prototype.addSlide=e.prototype.slickAdd=function(e,t,o){var s=this;if("boolean"==typeof t)o=t,t=null;else if(t<0||t>=s.slideCount)return!1;s.unload(),"number"==typeof t?0===t&&0===s.$slides.length?i(e).appendTo(s.$slideTrack):o?i(e).insertBefore(s.$slides.eq(t)):i(e).insertAfter(s.$slides.eq(t)):!0===o?i(e).prependTo(s.$slideTrack):i(e).appendTo(s.$slideTrack),s.$slides=s.$slideTrack.children(this.options.slide),s.$slideTrack.children(this.options.slide).detach(),s.$slideTrack.append(s.$slides),s.$slides.each(function(e,t){i(t).attr("data-slick-index",e)}),s.$slidesCache=s.$slides,s.reinit()},e.prototype.animateHeight=function(){var i=this;if(1===i.options.slidesToShow&&!0===i.options.adaptiveHeight&&!1===i.options.vertical){var e=i.$slides.eq(i.currentSlide).outerHeight(!0);i.$list.animate({height:e},i.options.speed)}},e.prototype.animateSlide=function(e,t){var o={},s=this;s.animateHeight(),!0===s.options.rtl&&!1===s.options.vertical&&(e=-e),!1===s.transformsEnabled?!1===s.options.vertical?s.$slideTrack.animate({left:e},s.options.speed,s.options.easing,t):s.$slideTrack.animate({top:e},s.options.speed,s.options.easing,t):!1===s.cssTransitions?(!0===s.options.rtl&&(s.currentLeft=-s.currentLeft),i({animStart:s.currentLeft}).animate({animStart:e},{duration:s.options.speed,easing:s.options.easing,step:function(i){i=Math.ceil(i),!1===s.options.vertical?(o[s.animType]="translate("+i+"px, 0px)",s.$slideTrack.css(o)):(o[s.animType]="translate(0px,"+i+"px)",s.$slideTrack.css(o))},complete:function(){t&&t.call()}})):(s.applyTransition(),e=Math.ceil(e),!1===s.options.vertical?o[s.animType]="translate3d("+e+"px, 0px, 0px)":o[s.animType]="translate3d(0px,"+e+"px, 0px)",s.$slideTrack.css(o),t&&setTimeout(function(){s.disableTransition(),t.call()},s.options.speed))},e.prototype.getNavTarget=function(){var e=this,t=e.options.asNavFor;return t&&null!==t&&(t=i(t).not(e.$slider)),t},e.prototype.asNavFor=function(e){var t=this.getNavTarget();null!==t&&"object"==typeof t&&t.each(function(){var t=i(this).slick("getSlick");t.unslicked||t.slideHandler(e,!0)})},e.prototype.applyTransition=function(i){var e=this,t={};!1===e.options.fade?t[e.transitionType]=e.transformType+" "+e.options.speed+"ms "+e.options.cssEase:t[e.transitionType]="opacity "+e.options.speed+"ms "+e.options.cssEase,!1===e.options.fade?e.$slideTrack.css(t):e.$slides.eq(i).css(t)},e.prototype.autoPlay=function(){var i=this;i.autoPlayClear(),i.slideCount>i.options.slidesToShow&&(i.autoPlayTimer=setInterval(i.autoPlayIterator,i.options.autoplaySpeed))},e.prototype.autoPlayClear=function(){var i=this;i.autoPlayTimer&&clearInterval(i.autoPlayTimer)},e.prototype.autoPlayIterator=function(){var i=this,e=i.currentSlide+i.options.slidesToScroll;i.paused||i.interrupted||i.focussed||(!1===i.options.infinite&&(1===i.direction&&i.currentSlide+1===i.slideCount-1?i.direction=0:0===i.direction&&(e=i.currentSlide-i.options.slidesToScroll,i.currentSlide-1==0&&(i.direction=1))),i.slideHandler(e))},e.prototype.buildArrows=function(){var e=this;!0===e.options.arrows&&(e.$prevArrow=i(e.options.prevArrow).addClass("slick-arrow"),e.$nextArrow=i(e.options.nextArrow).addClass("slick-arrow"),e.slideCount>e.options.slidesToShow?(e.$prevArrow.removeClass("slick-hidden").removeAttr("aria-hidden tabindex"),e.$nextArrow.removeClass("slick-hidden").removeAttr("aria-hidden tabindex"),e.htmlExpr.test(e.options.prevArrow)&&e.$prevArrow.prependTo(e.options.appendArrows),e.htmlExpr.test(e.options.nextArrow)&&e.$nextArrow.appendTo(e.options.appendArrows),!0!==e.options.infinite&&e.$prevArrow.addClass("slick-disabled").attr("aria-disabled","true")):e.$prevArrow.add(e.$nextArrow).addClass("slick-hidden").attr({"aria-disabled":"true",tabindex:"-1"}))},e.prototype.buildDots=function(){var e,t,o=this;if(!0===o.options.dots){for(o.$slider.addClass("slick-dotted"),t=i("
").addClass(o.options.dotsClass),e=0;e<=o.getDotCount();e+=1)t.append(i("").append(o.options.customPaging.call(this,o,e)));o.$dots=t.appendTo(o.options.appendDots),o.$dots.find("li").first().addClass("slick-active")}},e.prototype.buildOut=function(){var e=this;e.$slides=e.$slider.children(e.options.slide+":not(.slick-cloned)").addClass("slick-slide"),e.slideCount=e.$slides.length,e.$slides.each(function(e,t){i(t).attr("data-slick-index",e).data("originalStyling",i(t).attr("style")||"")}),e.$slider.addClass("slick-slider"),e.$slideTrack=0===e.slideCount?i('').appendTo(e.$slider):e.$slides.wrapAll('').parent(),e.$list=e.$slideTrack.wrap('').parent(),e.$slideTrack.css("opacity",0),!0!==e.options.centerMode&&!0!==e.options.swipeToSlide||(e.options.slidesToScroll=1),i("img[data-lazy]",e.$slider).not("[src]").addClass("slick-loading"),e.setupInfinite(),e.buildArrows(),e.buildDots(),e.updateDots(),e.setSlideClasses("number"==typeof e.currentSlide?e.currentSlide:0),!0===e.options.draggable&&e.$list.addClass("draggable")},e.prototype.buildRows=function(){var i,e,t,o,s,n,r,l=this;if(o=document.createDocumentFragment(),n=l.$slider.children(),l.options.rows>1){for(r=l.options.slidesPerRow*l.options.rows,s=Math.ceil(n.length/r),i=0;ir.breakpoints[o]&&(s=r.breakpoints[o]));null!==s?null!==r.activeBreakpoint?(s!==r.activeBreakpoint||t)&&(r.activeBreakpoint=s,"unslick"===r.breakpointSettings[s]?r.unslick(s):(r.options=i.extend({},r.originalSettings,r.breakpointSettings[s]),!0===e&&(r.currentSlide=r.options.initialSlide),r.refresh(e)),l=s):(r.activeBreakpoint=s,"unslick"===r.breakpointSettings[s]?r.unslick(s):(r.options=i.extend({},r.originalSettings,r.breakpointSettings[s]),!0===e&&(r.currentSlide=r.options.initialSlide),r.refresh(e)),l=s):null!==r.activeBreakpoint&&(r.activeBreakpoint=null,r.options=r.originalSettings,!0===e&&(r.currentSlide=r.options.initialSlide),r.refresh(e),l=s),e||!1===l||r.$slider.trigger("breakpoint",[r,l])}},e.prototype.changeSlide=function(e,t){var o,s,n,r=this,l=i(e.currentTarget);switch(l.is("a")&&e.preventDefault(),l.is("li")||(l=l.closest("li")),n=r.slideCount%r.options.slidesToScroll!=0,o=n?0:(r.slideCount-r.currentSlide)%r.options.slidesToScroll,e.data.message){case"previous":s=0===o?r.options.slidesToScroll:r.options.slidesToShow-o,r.slideCount>r.options.slidesToShow&&r.slideHandler(r.currentSlide-s,!1,t);break;case"next":s=0===o?r.options.slidesToScroll:o,r.slideCount>r.options.slidesToShow&&r.slideHandler(r.currentSlide+s,!1,t);break;case"index":var d=0===e.data.index?0:e.data.index||l.index()*r.options.slidesToScroll;r.slideHandler(r.checkNavigable(d),!1,t),l.children().trigger("focus");break;default:return}},e.prototype.checkNavigable=function(i){var e,t;if(e=this.getNavigableIndexes(),t=0,i>e[e.length-1])i=e[e.length-1];else for(var o in e){if(ie.options.slidesToShow&&(e.$prevArrow&&e.$prevArrow.off("click.slick",e.changeSlide),e.$nextArrow&&e.$nextArrow.off("click.slick",e.changeSlide),!0===e.options.accessibility&&(e.$prevArrow&&e.$prevArrow.off("keydown.slick",e.keyHandler),e.$nextArrow&&e.$nextArrow.off("keydown.slick",e.keyHandler))),e.$list.off("touchstart.slick mousedown.slick",e.swipeHandler),e.$list.off("touchmove.slick mousemove.slick",e.swipeHandler),e.$list.off("touchend.slick mouseup.slick",e.swipeHandler),e.$list.off("touchcancel.slick mouseleave.slick",e.swipeHandler),e.$list.off("click.slick",e.clickHandler),i(document).off(e.visibilityChange,e.visibility),e.cleanUpSlideEvents(),!0===e.options.accessibility&&e.$list.off("keydown.slick",e.keyHandler),!0===e.options.focusOnSelect&&i(e.$slideTrack).children().off("click.slick",e.selectHandler),i(window).off("orientationchange.slick.slick-"+e.instanceUid,e.orientationChange),i(window).off("resize.slick.slick-"+e.instanceUid,e.resize),i("[draggable!=true]",e.$slideTrack).off("dragstart",e.preventDefault),i(window).off("load.slick.slick-"+e.instanceUid,e.setPosition)},e.prototype.cleanUpSlideEvents=function(){var e=this;e.$list.off("mouseenter.slick",i.proxy(e.interrupt,e,!0)),e.$list.off("mouseleave.slick",i.proxy(e.interrupt,e,!1))},e.prototype.cleanUpRows=function(){var i,e=this;e.options.rows>1&&((i=e.$slides.children().children()).removeAttr("style"),e.$slider.empty().append(i))},e.prototype.clickHandler=function(i){!1===this.shouldClick&&(i.stopImmediatePropagation(),i.stopPropagation(),i.preventDefault())},e.prototype.destroy=function(e){var t=this;t.autoPlayClear(),t.touchObject={},t.cleanUpEvents(),i(".slick-cloned",t.$slider).detach(),t.$dots&&t.$dots.remove(),t.$prevArrow&&t.$prevArrow.length&&(t.$prevArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display",""),t.htmlExpr.test(t.options.prevArrow)&&t.$prevArrow.remove()),t.$nextArrow&&t.$nextArrow.length&&(t.$nextArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display",""),t.htmlExpr.test(t.options.nextArrow)&&t.$nextArrow.remove()),t.$slides&&(t.$slides.removeClass("slick-slide slick-active slick-center slick-visible slick-current").removeAttr("aria-hidden").removeAttr("data-slick-index").each(function(){i(this).attr("style",i(this).data("originalStyling"))}),t.$slideTrack.children(this.options.slide).detach(),t.$slideTrack.detach(),t.$list.detach(),t.$slider.append(t.$slides)),t.cleanUpRows(),t.$slider.removeClass("slick-slider"),t.$slider.removeClass("slick-initialized"),t.$slider.removeClass("slick-dotted"),t.unslicked=!0,e||t.$slider.trigger("destroy",[t])},e.prototype.disableTransition=function(i){var e=this,t={};t[e.transitionType]="",!1===e.options.fade?e.$slideTrack.css(t):e.$slides.eq(i).css(t)},e.prototype.fadeSlide=function(i,e){var t=this;!1===t.cssTransitions?(t.$slides.eq(i).css({zIndex:t.options.zIndex}),t.$slides.eq(i).animate({opacity:1},t.options.speed,t.options.easing,e)):(t.applyTransition(i),t.$slides.eq(i).css({opacity:1,zIndex:t.options.zIndex}),e&&setTimeout(function(){t.disableTransition(i),e.call()},t.options.speed))},e.prototype.fadeSlideOut=function(i){var e=this;!1===e.cssTransitions?e.$slides.eq(i).animate({opacity:0,zIndex:e.options.zIndex-2},e.options.speed,e.options.easing):(e.applyTransition(i),e.$slides.eq(i).css({opacity:0,zIndex:e.options.zIndex-2}))},e.prototype.filterSlides=e.prototype.slickFilter=function(i){var e=this;null!==i&&(e.$slidesCache=e.$slides,e.unload(),e.$slideTrack.children(this.options.slide).detach(),e.$slidesCache.filter(i).appendTo(e.$slideTrack),e.reinit())},e.prototype.focusHandler=function(){var e=this;e.$slider.off("focus.slick blur.slick").on("focus.slick blur.slick","*",function(t){t.stopImmediatePropagation();var o=i(this);setTimeout(function(){e.options.pauseOnFocus&&(e.focussed=o.is(":focus"),e.autoPlay())},0)})},e.prototype.getCurrent=e.prototype.slickCurrentSlide=function(){return this.currentSlide},e.prototype.getDotCount=function(){var i=this,e=0,t=0,o=0;if(!0===i.options.infinite)if(i.slideCount<=i.options.slidesToShow)++o;else for(;en.options.slidesToShow&&(n.slideOffset=n.slideWidth*n.options.slidesToShow*-1,s=-1,!0===n.options.vertical&&!0===n.options.centerMode&&(2===n.options.slidesToShow?s=-1.5:1===n.options.slidesToShow&&(s=-2)),r=t*n.options.slidesToShow*s),n.slideCount%n.options.slidesToScroll!=0&&i+n.options.slidesToScroll>n.slideCount&&n.slideCount>n.options.slidesToShow&&(i>n.slideCount?(n.slideOffset=(n.options.slidesToShow-(i-n.slideCount))*n.slideWidth*-1,r=(n.options.slidesToShow-(i-n.slideCount))*t*-1):(n.slideOffset=n.slideCount%n.options.slidesToScroll*n.slideWidth*-1,r=n.slideCount%n.options.slidesToScroll*t*-1))):i+n.options.slidesToShow>n.slideCount&&(n.slideOffset=(i+n.options.slidesToShow-n.slideCount)*n.slideWidth,r=(i+n.options.slidesToShow-n.slideCount)*t),n.slideCount<=n.options.slidesToShow&&(n.slideOffset=0,r=0),!0===n.options.centerMode&&n.slideCount<=n.options.slidesToShow?n.slideOffset=n.slideWidth*Math.floor(n.options.slidesToShow)/2-n.slideWidth*n.slideCount/2:!0===n.options.centerMode&&!0===n.options.infinite?n.slideOffset+=n.slideWidth*Math.floor(n.options.slidesToShow/2)-n.slideWidth:!0===n.options.centerMode&&(n.slideOffset=0,n.slideOffset+=n.slideWidth*Math.floor(n.options.slidesToShow/2)),e=!1===n.options.vertical?i*n.slideWidth*-1+n.slideOffset:i*t*-1+r,!0===n.options.variableWidth&&(o=n.slideCount<=n.options.slidesToShow||!1===n.options.infinite?n.$slideTrack.children(".slick-slide").eq(i):n.$slideTrack.children(".slick-slide").eq(i+n.options.slidesToShow),e=!0===n.options.rtl?o[0]?-1*(n.$slideTrack.width()-o[0].offsetLeft-o.width()):0:o[0]?-1*o[0].offsetLeft:0,!0===n.options.centerMode&&(o=n.slideCount<=n.options.slidesToShow||!1===n.options.infinite?n.$slideTrack.children(".slick-slide").eq(i):n.$slideTrack.children(".slick-slide").eq(i+n.options.slidesToShow+1),e=!0===n.options.rtl?o[0]?-1*(n.$slideTrack.width()-o[0].offsetLeft-o.width()):0:o[0]?-1*o[0].offsetLeft:0,e+=(n.$list.width()-o.outerWidth())/2)),e},e.prototype.getOption=e.prototype.slickGetOption=function(i){return this.options[i]},e.prototype.getNavigableIndexes=function(){var i,e=this,t=0,o=0,s=[];for(!1===e.options.infinite?i=e.slideCount:(t=-1*e.options.slidesToScroll,o=-1*e.options.slidesToScroll,i=2*e.slideCount);t-1*o.swipeLeft)return e=n,!1}),Math.abs(i(e).attr("data-slick-index")-o.currentSlide)||1):o.options.slidesToScroll},e.prototype.goTo=e.prototype.slickGoTo=function(i,e){this.changeSlide({data:{message:"index",index:parseInt(i)}},e)},e.prototype.init=function(e){var t=this;i(t.$slider).hasClass("slick-initialized")||(i(t.$slider).addClass("slick-initialized"),t.buildRows(),t.buildOut(),t.setProps(),t.startLoad(),t.loadSlider(),t.initializeEvents(),t.updateArrows(),t.updateDots(),t.checkResponsive(!0),t.focusHandler()),e&&t.$slider.trigger("init",[t]),!0===t.options.accessibility&&t.initADA(),t.options.autoplay&&(t.paused=!1,t.autoPlay())},e.prototype.initADA=function(){var e=this,t=Math.ceil(e.slideCount/e.options.slidesToShow),o=e.getNavigableIndexes().filter(function(i){return i>=0&&ii.options.slidesToShow&&(i.$prevArrow.off("click.slick").on("click.slick",{message:"previous"},i.changeSlide),i.$nextArrow.off("click.slick").on("click.slick",{message:"next"},i.changeSlide),!0===i.options.accessibility&&(i.$prevArrow.on("keydown.slick",i.keyHandler),i.$nextArrow.on("keydown.slick",i.keyHandler)))},e.prototype.initDotEvents=function(){var e=this;!0===e.options.dots&&(i("li",e.$dots).on("click.slick",{message:"index"},e.changeSlide),!0===e.options.accessibility&&e.$dots.on("keydown.slick",e.keyHandler)),!0===e.options.dots&&!0===e.options.pauseOnDotsHover&&i("li",e.$dots).on("mouseenter.slick",i.proxy(e.interrupt,e,!0)).on("mouseleave.slick",i.proxy(e.interrupt,e,!1))},e.prototype.initSlideEvents=function(){var e=this;e.options.pauseOnHover&&(e.$list.on("mouseenter.slick",i.proxy(e.interrupt,e,!0)),e.$list.on("mouseleave.slick",i.proxy(e.interrupt,e,!1)))},e.prototype.initializeEvents=function(){var e=this;e.initArrowEvents(),e.initDotEvents(),e.initSlideEvents(),e.$list.on("touchstart.slick mousedown.slick",{action:"start"},e.swipeHandler),e.$list.on("touchmove.slick mousemove.slick",{action:"move"},e.swipeHandler),e.$list.on("touchend.slick mouseup.slick",{action:"end"},e.swipeHandler),e.$list.on("touchcancel.slick mouseleave.slick",{action:"end"},e.swipeHandler),e.$list.on("click.slick",e.clickHandler),i(document).on(e.visibilityChange,i.proxy(e.visibility,e)),!0===e.options.accessibility&&e.$list.on("keydown.slick",e.keyHandler),!0===e.options.focusOnSelect&&i(e.$slideTrack).children().on("click.slick",e.selectHandler),i(window).on("orientationchange.slick.slick-"+e.instanceUid,i.proxy(e.orientationChange,e)),i(window).on("resize.slick.slick-"+e.instanceUid,i.proxy(e.resize,e)),i("[draggable!=true]",e.$slideTrack).on("dragstart",e.preventDefault),i(window).on("load.slick.slick-"+e.instanceUid,e.setPosition),i(e.setPosition)},e.prototype.initUI=function(){var i=this;!0===i.options.arrows&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow.show(),i.$nextArrow.show()),!0===i.options.dots&&i.slideCount>i.options.slidesToShow&&i.$dots.show()},e.prototype.keyHandler=function(i){var e=this;i.target.tagName.match("TEXTAREA|INPUT|SELECT")||(37===i.keyCode&&!0===e.options.accessibility?e.changeSlide({data:{message:!0===e.options.rtl?"next":"previous"}}):39===i.keyCode&&!0===e.options.accessibility&&e.changeSlide({data:{message:!0===e.options.rtl?"previous":"next"}}))},e.prototype.lazyLoad=function(){function e(e){i("img[data-lazy]",e).each(function(){var e=i(this),t=i(this).attr("data-lazy"),o=i(this).attr("data-srcset"),s=i(this).attr("data-sizes")||n.$slider.attr("data-sizes"),r=document.createElement("img");r.onload=function(){e.animate({opacity:0},100,function(){o&&(e.attr("srcset",o),s&&e.attr("sizes",s)),e.attr("src",t).animate({opacity:1},200,function(){e.removeAttr("data-lazy data-srcset data-sizes").removeClass("slick-loading")}),n.$slider.trigger("lazyLoaded",[n,e,t])})},r.onerror=function(){e.removeAttr("data-lazy").removeClass("slick-loading").addClass("slick-lazyload-error"),n.$slider.trigger("lazyLoadError",[n,e,t])},r.src=t})}var t,o,s,n=this;if(!0===n.options.centerMode?!0===n.options.infinite?s=(o=n.currentSlide+(n.options.slidesToShow/2+1))+n.options.slidesToShow+2:(o=Math.max(0,n.currentSlide-(n.options.slidesToShow/2+1)),s=n.options.slidesToShow/2+1+2+n.currentSlide):(o=n.options.infinite?n.options.slidesToShow+n.currentSlide:n.currentSlide,s=Math.ceil(o+n.options.slidesToShow),!0===n.options.fade&&(o>0&&o--,s<=n.slideCount&&s++)),t=n.$slider.find(".slick-slide").slice(o,s),"anticipated"===n.options.lazyLoad)for(var r=o-1,l=s,d=n.$slider.find(".slick-slide"),a=0;a=n.slideCount-n.options.slidesToShow?e(n.$slider.find(".slick-cloned").slice(0,n.options.slidesToShow)):0===n.currentSlide&&e(n.$slider.find(".slick-cloned").slice(-1*n.options.slidesToShow))},e.prototype.loadSlider=function(){var i=this;i.setPosition(),i.$slideTrack.css({opacity:1}),i.$slider.removeClass("slick-loading"),i.initUI(),"progressive"===i.options.lazyLoad&&i.progressiveLazyLoad()},e.prototype.next=e.prototype.slickNext=function(){this.changeSlide({data:{message:"next"}})},e.prototype.orientationChange=function(){var i=this;i.checkResponsive(),i.setPosition()},e.prototype.pause=e.prototype.slickPause=function(){var i=this;i.autoPlayClear(),i.paused=!0},e.prototype.play=e.prototype.slickPlay=function(){var i=this;i.autoPlay(),i.options.autoplay=!0,i.paused=!1,i.focussed=!1,i.interrupted=!1},e.prototype.postSlide=function(e){var t=this;t.unslicked||(t.$slider.trigger("afterChange",[t,e]),t.animating=!1,t.slideCount>t.options.slidesToShow&&t.setPosition(),t.swipeLeft=null,t.options.autoplay&&t.autoPlay(),!0===t.options.accessibility&&(t.initADA(),t.options.focusOnChange&&i(t.$slides.get(t.currentSlide)).attr("tabindex",0).focus()))},e.prototype.prev=e.prototype.slickPrev=function(){this.changeSlide({data:{message:"previous"}})},e.prototype.preventDefault=function(i){i.preventDefault()},e.prototype.progressiveLazyLoad=function(e){e=e||1;var t,o,s,n,r,l=this,d=i("img[data-lazy]",l.$slider);d.length?(t=d.first(),o=t.attr("data-lazy"),s=t.attr("data-srcset"),n=t.attr("data-sizes")||l.$slider.attr("data-sizes"),(r=document.createElement("img")).onload=function(){s&&(t.attr("srcset",s),n&&t.attr("sizes",n)),t.attr("src",o).removeAttr("data-lazy data-srcset data-sizes").removeClass("slick-loading"),!0===l.options.adaptiveHeight&&l.setPosition(),l.$slider.trigger("lazyLoaded",[l,t,o]),l.progressiveLazyLoad()},r.onerror=function(){e<3?setTimeout(function(){l.progressiveLazyLoad(e+1)},500):(t.removeAttr("data-lazy").removeClass("slick-loading").addClass("slick-lazyload-error"),l.$slider.trigger("lazyLoadError",[l,t,o]),l.progressiveLazyLoad())},r.src=o):l.$slider.trigger("allImagesLoaded",[l])},e.prototype.refresh=function(e){var t,o,s=this;o=s.slideCount-s.options.slidesToShow,!s.options.infinite&&s.currentSlide>o&&(s.currentSlide=o),s.slideCount<=s.options.slidesToShow&&(s.currentSlide=0),t=s.currentSlide,s.destroy(!0),i.extend(s,s.initials,{currentSlide:t}),s.init(),e||s.changeSlide({data:{message:"index",index:t}},!1)},e.prototype.registerBreakpoints=function(){var e,t,o,s=this,n=s.options.responsive||null;if("array"===i.type(n)&&n.length){s.respondTo=s.options.respondTo||"window";for(e in n)if(o=s.breakpoints.length-1,n.hasOwnProperty(e)){for(t=n[e].breakpoint;o>=0;)s.breakpoints[o]&&s.breakpoints[o]===t&&s.breakpoints.splice(o,1),o--;s.breakpoints.push(t),s.breakpointSettings[t]=n[e].settings}s.breakpoints.sort(function(i,e){return s.options.mobileFirst?i-e:e-i})}},e.prototype.reinit=function(){var e=this;e.$slides=e.$slideTrack.children(e.options.slide).addClass("slick-slide"),e.slideCount=e.$slides.length,e.currentSlide>=e.slideCount&&0!==e.currentSlide&&(e.currentSlide=e.currentSlide-e.options.slidesToScroll),e.slideCount<=e.options.slidesToShow&&(e.currentSlide=0),e.registerBreakpoints(),e.setProps(),e.setupInfinite(),e.buildArrows(),e.updateArrows(),e.initArrowEvents(),e.buildDots(),e.updateDots(),e.initDotEvents(),e.cleanUpSlideEvents(),e.initSlideEvents(),e.checkResponsive(!1,!0),!0===e.options.focusOnSelect&&i(e.$slideTrack).children().on("click.slick",e.selectHandler),e.setSlideClasses("number"==typeof e.currentSlide?e.currentSlide:0),e.setPosition(),e.focusHandler(),e.paused=!e.options.autoplay,e.autoPlay(),e.$slider.trigger("reInit",[e])},e.prototype.resize=function(){var e=this;i(window).width()!==e.windowWidth&&(clearTimeout(e.windowDelay),e.windowDelay=window.setTimeout(function(){e.windowWidth=i(window).width(),e.checkResponsive(),e.unslicked||e.setPosition()},50))},e.prototype.removeSlide=e.prototype.slickRemove=function(i,e,t){var o=this;if(i="boolean"==typeof i?!0===(e=i)?0:o.slideCount-1:!0===e?--i:i,o.slideCount<1||i<0||i>o.slideCount-1)return!1;o.unload(),!0===t?o.$slideTrack.children().remove():o.$slideTrack.children(this.options.slide).eq(i).remove(),o.$slides=o.$slideTrack.children(this.options.slide),o.$slideTrack.children(this.options.slide).detach(),o.$slideTrack.append(o.$slides),o.$slidesCache=o.$slides,o.reinit()},e.prototype.setCSS=function(i){var e,t,o=this,s={};!0===o.options.rtl&&(i=-i),e="left"==o.positionProp?Math.ceil(i)+"px":"0px",t="top"==o.positionProp?Math.ceil(i)+"px":"0px",s[o.positionProp]=i,!1===o.transformsEnabled?o.$slideTrack.css(s):(s={},!1===o.cssTransitions?(s[o.animType]="translate("+e+", "+t+")",o.$slideTrack.css(s)):(s[o.animType]="translate3d("+e+", "+t+", 0px)",o.$slideTrack.css(s)))},e.prototype.setDimensions=function(){var i=this;!1===i.options.vertical?!0===i.options.centerMode&&i.$list.css({padding:"0px "+i.options.centerPadding}):(i.$list.height(i.$slides.first().outerHeight(!0)*i.options.slidesToShow),!0===i.options.centerMode&&i.$list.css({padding:i.options.centerPadding+" 0px"})),i.listWidth=i.$list.width(),i.listHeight=i.$list.height(),!1===i.options.vertical&&!1===i.options.variableWidth?(i.slideWidth=Math.ceil(i.listWidth/i.options.slidesToShow),i.$slideTrack.width(Math.ceil(i.slideWidth*i.$slideTrack.children(".slick-slide").length))):!0===i.options.variableWidth?i.$slideTrack.width(5e3*i.slideCount):(i.slideWidth=Math.ceil(i.listWidth),i.$slideTrack.height(Math.ceil(i.$slides.first().outerHeight(!0)*i.$slideTrack.children(".slick-slide").length)));var e=i.$slides.first().outerWidth(!0)-i.$slides.first().width();!1===i.options.variableWidth&&i.$slideTrack.children(".slick-slide").width(i.slideWidth-e)},e.prototype.setFade=function(){var e,t=this;t.$slides.each(function(o,s){e=t.slideWidth*o*-1,!0===t.options.rtl?i(s).css({position:"relative",right:e,top:0,zIndex:t.options.zIndex-2,opacity:0}):i(s).css({position:"relative",left:e,top:0,zIndex:t.options.zIndex-2,opacity:0})}),t.$slides.eq(t.currentSlide).css({zIndex:t.options.zIndex-1,opacity:1})},e.prototype.setHeight=function(){var i=this;if(1===i.options.slidesToShow&&!0===i.options.adaptiveHeight&&!1===i.options.vertical){var e=i.$slides.eq(i.currentSlide).outerHeight(!0);i.$list.css("height",e)}},e.prototype.setOption=e.prototype.slickSetOption=function(){var e,t,o,s,n,r=this,l=!1;if("object"===i.type(arguments[0])?(o=arguments[0],l=arguments[1],n="multiple"):"string"===i.type(arguments[0])&&(o=arguments[0],s=arguments[1],l=arguments[2],"responsive"===arguments[0]&&"array"===i.type(arguments[1])?n="responsive":void 0!==arguments[1]&&(n="single")),"single"===n)r.options[o]=s;else if("multiple"===n)i.each(o,function(i,e){r.options[i]=e});else if("responsive"===n)for(t in s)if("array"!==i.type(r.options.responsive))r.options.responsive=[s[t]];else{for(e=r.options.responsive.length-1;e>=0;)r.options.responsive[e].breakpoint===s[t].breakpoint&&r.options.responsive.splice(e,1),e--;r.options.responsive.push(s[t])}l&&(r.unload(),r.reinit())},e.prototype.setPosition=function(){var i=this;i.setDimensions(),i.setHeight(),!1===i.options.fade?i.setCSS(i.getLeft(i.currentSlide)):i.setFade(),i.$slider.trigger("setPosition",[i])},e.prototype.setProps=function(){var i=this,e=document.body.style;i.positionProp=!0===i.options.vertical?"top":"left","top"===i.positionProp?i.$slider.addClass("slick-vertical"):i.$slider.removeClass("slick-vertical"),void 0===e.WebkitTransition&&void 0===e.MozTransition&&void 0===e.msTransition||!0===i.options.useCSS&&(i.cssTransitions=!0),i.options.fade&&("number"==typeof i.options.zIndex?i.options.zIndex<3&&(i.options.zIndex=3):i.options.zIndex=i.defaults.zIndex),void 0!==e.OTransform&&(i.animType="OTransform",i.transformType="-o-transform",i.transitionType="OTransition",void 0===e.perspectiveProperty&&void 0===e.webkitPerspective&&(i.animType=!1)),void 0!==e.MozTransform&&(i.animType="MozTransform",i.transformType="-moz-transform",i.transitionType="MozTransition",void 0===e.perspectiveProperty&&void 0===e.MozPerspective&&(i.animType=!1)),void 0!==e.webkitTransform&&(i.animType="webkitTransform",i.transformType="-webkit-transform",i.transitionType="webkitTransition",void 0===e.perspectiveProperty&&void 0===e.webkitPerspective&&(i.animType=!1)),void 0!==e.msTransform&&(i.animType="msTransform",i.transformType="-ms-transform",i.transitionType="msTransition",void 0===e.msTransform&&(i.animType=!1)),void 0!==e.transform&&!1!==i.animType&&(i.animType="transform",i.transformType="transform",i.transitionType="transition"),i.transformsEnabled=i.options.useTransform&&null!==i.animType&&!1!==i.animType},e.prototype.setSlideClasses=function(i){var e,t,o,s,n=this;if(t=n.$slider.find(".slick-slide").removeClass("slick-active slick-center slick-current").attr("aria-hidden","true"),n.$slides.eq(i).addClass("slick-current"),!0===n.options.centerMode){var r=n.options.slidesToShow%2==0?1:0;e=Math.floor(n.options.slidesToShow/2),!0===n.options.infinite&&(i>=e&&i<=n.slideCount-1-e?n.$slides.slice(i-e+r,i+e+1).addClass("slick-active").attr("aria-hidden","false"):(o=n.options.slidesToShow+i,t.slice(o-e+1+r,o+e+2).addClass("slick-active").attr("aria-hidden","false")),0===i?t.eq(t.length-1-n.options.slidesToShow).addClass("slick-center"):i===n.slideCount-1&&t.eq(n.options.slidesToShow).addClass("slick-center")),n.$slides.eq(i).addClass("slick-center")}else i>=0&&i<=n.slideCount-n.options.slidesToShow?n.$slides.slice(i,i+n.options.slidesToShow).addClass("slick-active").attr("aria-hidden","false"):t.length<=n.options.slidesToShow?t.addClass("slick-active").attr("aria-hidden","false"):(s=n.slideCount%n.options.slidesToShow,o=!0===n.options.infinite?n.options.slidesToShow+i:i,n.options.slidesToShow==n.options.slidesToScroll&&n.slideCount-is.options.slidesToShow)){for(o=!0===s.options.centerMode?s.options.slidesToShow+1:s.options.slidesToShow,e=s.slideCount;e>s.slideCount-o;e-=1)t=e-1,i(s.$slides[t]).clone(!0).attr("id","").attr("data-slick-index",t-s.slideCount).prependTo(s.$slideTrack).addClass("slick-cloned");for(e=0;ea.getDotCount()*a.options.slidesToScroll))!1===a.options.fade&&(o=a.currentSlide,!0!==t?a.animateSlide(r,function(){a.postSlide(o)}):a.postSlide(o));else if(!1===a.options.infinite&&!0===a.options.centerMode&&(i<0||i>a.slideCount-a.options.slidesToScroll))!1===a.options.fade&&(o=a.currentSlide,!0!==t?a.animateSlide(r,function(){a.postSlide(o)}):a.postSlide(o));else{if(a.options.autoplay&&clearInterval(a.autoPlayTimer),s=o<0?a.slideCount%a.options.slidesToScroll!=0?a.slideCount-a.slideCount%a.options.slidesToScroll:a.slideCount+o:o>=a.slideCount?a.slideCount%a.options.slidesToScroll!=0?0:o-a.slideCount:o,a.animating=!0,a.$slider.trigger("beforeChange",[a,a.currentSlide,s]),n=a.currentSlide,a.currentSlide=s,a.setSlideClasses(a.currentSlide),a.options.asNavFor&&(l=(l=a.getNavTarget()).slick("getSlick")).slideCount<=l.options.slidesToShow&&l.setSlideClasses(a.currentSlide),a.updateDots(),a.updateArrows(),!0===a.options.fade)return!0!==t?(a.fadeSlideOut(n),a.fadeSlide(s,function(){a.postSlide(s)})):a.postSlide(s),void a.animateHeight();!0!==t?a.animateSlide(d,function(){a.postSlide(s)}):a.postSlide(s)}},e.prototype.startLoad=function(){var i=this;!0===i.options.arrows&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow.hide(),i.$nextArrow.hide()),!0===i.options.dots&&i.slideCount>i.options.slidesToShow&&i.$dots.hide(),i.$slider.addClass("slick-loading")},e.prototype.swipeDirection=function(){var i,e,t,o,s=this;return i=s.touchObject.startX-s.touchObject.curX,e=s.touchObject.startY-s.touchObject.curY,t=Math.atan2(e,i),(o=Math.round(180*t/Math.PI))<0&&(o=360-Math.abs(o)),o<=45&&o>=0?!1===s.options.rtl?"left":"right":o<=360&&o>=315?!1===s.options.rtl?"left":"right":o>=135&&o<=225?!1===s.options.rtl?"right":"left":!0===s.options.verticalSwiping?o>=35&&o<=135?"down":"up":"vertical"},e.prototype.swipeEnd=function(i){var e,t,o=this;if(o.dragging=!1,o.swiping=!1,o.scrolling)return o.scrolling=!1,!1;if(o.interrupted=!1,o.shouldClick=!(o.touchObject.swipeLength>10),void 0===o.touchObject.curX)return!1;if(!0===o.touchObject.edgeHit&&o.$slider.trigger("edge",[o,o.swipeDirection()]),o.touchObject.swipeLength>=o.touchObject.minSwipe){switch(t=o.swipeDirection()){case"left":case"down":e=o.options.swipeToSlide?o.checkNavigable(o.currentSlide+o.getSlideCount()):o.currentSlide+o.getSlideCount(),o.currentDirection=0;break;case"right":case"up":e=o.options.swipeToSlide?o.checkNavigable(o.currentSlide-o.getSlideCount()):o.currentSlide-o.getSlideCount(),o.currentDirection=1}"vertical"!=t&&(o.slideHandler(e),o.touchObject={},o.$slider.trigger("swipe",[o,t]))}else o.touchObject.startX!==o.touchObject.curX&&(o.slideHandler(o.currentSlide),o.touchObject={})},e.prototype.swipeHandler=function(i){var e=this;if(!(!1===e.options.swipe||"ontouchend"in document&&!1===e.options.swipe||!1===e.options.draggable&&-1!==i.type.indexOf("mouse")))switch(e.touchObject.fingerCount=i.originalEvent&&void 0!==i.originalEvent.touches?i.originalEvent.touches.length:1,e.touchObject.minSwipe=e.listWidth/e.options.touchThreshold,!0===e.options.verticalSwiping&&(e.touchObject.minSwipe=e.listHeight/e.options.touchThreshold),i.data.action){case"start":e.swipeStart(i);break;case"move":e.swipeMove(i);break;case"end":e.swipeEnd(i)}},e.prototype.swipeMove=function(i){var e,t,o,s,n,r,l=this;return n=void 0!==i.originalEvent?i.originalEvent.touches:null,!(!l.dragging||l.scrolling||n&&1!==n.length)&&(e=l.getLeft(l.currentSlide),l.touchObject.curX=void 0!==n?n[0].pageX:i.clientX,l.touchObject.curY=void 0!==n?n[0].pageY:i.clientY,l.touchObject.swipeLength=Math.round(Math.sqrt(Math.pow(l.touchObject.curX-l.touchObject.startX,2))),r=Math.round(Math.sqrt(Math.pow(l.touchObject.curY-l.touchObject.startY,2))),!l.options.verticalSwiping&&!l.swiping&&r>4?(l.scrolling=!0,!1):(!0===l.options.verticalSwiping&&(l.touchObject.swipeLength=r),t=l.swipeDirection(),void 0!==i.originalEvent&&l.touchObject.swipeLength>4&&(l.swiping=!0,i.preventDefault()),s=(!1===l.options.rtl?1:-1)*(l.touchObject.curX>l.touchObject.startX?1:-1),!0===l.options.verticalSwiping&&(s=l.touchObject.curY>l.touchObject.startY?1:-1),o=l.touchObject.swipeLength,l.touchObject.edgeHit=!1,!1===l.options.infinite&&(0===l.currentSlide&&"right"===t||l.currentSlide>=l.getDotCount()&&"left"===t)&&(o=l.touchObject.swipeLength*l.options.edgeFriction,l.touchObject.edgeHit=!0),!1===l.options.vertical?l.swipeLeft=e+o*s:l.swipeLeft=e+o*(l.$list.height()/l.listWidth)*s,!0===l.options.verticalSwiping&&(l.swipeLeft=e+o*s),!0!==l.options.fade&&!1!==l.options.touchMove&&(!0===l.animating?(l.swipeLeft=null,!1):void l.setCSS(l.swipeLeft))))},e.prototype.swipeStart=function(i){var e,t=this;if(t.interrupted=!0,1!==t.touchObject.fingerCount||t.slideCount<=t.options.slidesToShow)return t.touchObject={},!1;void 0!==i.originalEvent&&void 0!==i.originalEvent.touches&&(e=i.originalEvent.touches[0]),t.touchObject.startX=t.touchObject.curX=void 0!==e?e.pageX:i.clientX,t.touchObject.startY=t.touchObject.curY=void 0!==e?e.pageY:i.clientY,t.dragging=!0},e.prototype.unfilterSlides=e.prototype.slickUnfilter=function(){var i=this;null!==i.$slidesCache&&(i.unload(),i.$slideTrack.children(this.options.slide).detach(),i.$slidesCache.appendTo(i.$slideTrack),i.reinit())},e.prototype.unload=function(){var e=this;i(".slick-cloned",e.$slider).remove(),e.$dots&&e.$dots.remove(),e.$prevArrow&&e.htmlExpr.test(e.options.prevArrow)&&e.$prevArrow.remove(),e.$nextArrow&&e.htmlExpr.test(e.options.nextArrow)&&e.$nextArrow.remove(),e.$slides.removeClass("slick-slide slick-active slick-visible slick-current").attr("aria-hidden","true").css("width","")},e.prototype.unslick=function(i){var e=this;e.$slider.trigger("unslick",[e,i]),e.destroy()},e.prototype.updateArrows=function(){var i=this;Math.floor(i.options.slidesToShow/2),!0===i.options.arrows&&i.slideCount>i.options.slidesToShow&&!i.options.infinite&&(i.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false"),i.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false"),0===i.currentSlide?(i.$prevArrow.addClass("slick-disabled").attr("aria-disabled","true"),i.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false")):i.currentSlide>=i.slideCount-i.options.slidesToShow&&!1===i.options.centerMode?(i.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true"),i.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")):i.currentSlide>=i.slideCount-1&&!0===i.options.centerMode&&(i.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true"),i.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")))},e.prototype.updateDots=function(){var i=this;null!==i.$dots&&(i.$dots.find("li").removeClass("slick-active").end(),i.$dots.find("li").eq(Math.floor(i.currentSlide/i.options.slidesToScroll)).addClass("slick-active"))},e.prototype.visibility=function(){var i=this;i.options.autoplay&&(document[i.hidden]?i.interrupted=!0:i.interrupted=!1)},i.fn.slick=function(){var i,t,o=this,s=arguments[0],n=Array.prototype.slice.call(arguments,1),r=o.length;for(i=0;i 0)) {
node.state.expanded = true;
}
else {
node.state.expanded = false;
}
}
if (!node.state.hasOwnProperty('selected')) {
node.state.selected = false;
}
_this.nodes.push(node);
if (node.nodes) {
_this.setInitialStates(node, level);
}
});
};
Tree.prototype.clickHandler = function (event) {
if (!this.options.enableLinks) event.preventDefault();
var target = $(event.target);
var node = this.findNode(target);
if (!node || node.state.disabled) return;
var classList = target.attr('class') ? target.attr('class').split(' ') : [];
if ((classList.indexOf('expand-icon') !== -1)) {
this.toggleExpandedState(node, _default.options);
this.render();
}
else if ((classList.indexOf('check-icon') !== -1)) {
this.toggleCheckedState(node, _default.options);
this.render();
}
else {
if (node.selectable) {
this.toggleSelectedState(node, _default.options);
} else {
this.toggleExpandedState(node, _default.options);
}
this.render();
}
};
Tree.prototype.findNode = function (target) {
var nodeId = target.closest('li.list-group-item').attr('data-nodeid');
var node = this.nodes[nodeId];
if (!node) {
console.log('Error: node does not exist');
}
return node;
};
Tree.prototype.toggleExpandedState = function (node, options) {
if (!node) return;
this.setExpandedState(node, !node.state.expanded, options);
};
Tree.prototype.setExpandedState = function (node, state, options) {
if (state === node.state.expanded) return;
if (state && node.nodes) {
node.state.expanded = true;
if (!options.silent) {
this.$element.trigger('nodeExpanded', $.extend(true, {}, node));
}
}
else if (!state) {
node.state.expanded = false;
if (!options.silent) {
this.$element.trigger('nodeCollapsed', $.extend(true, {}, node));
}
if (node.nodes && !options.ignoreChildren) {
$.each(node.nodes, $.proxy(function (index, node) {
this.setExpandedState(node, false, options);
}, this));
}
}
};
Tree.prototype.toggleSelectedState = function (node, options) {
if (!node) return;
this.setSelectedState(node, !node.state.selected, options);
};
Tree.prototype.setSelectedState = function (node, state, options) {
if (state === node.state.selected) return;
if (state) {
if (!this.options.multiSelect) {
$.each(this.findNodes('true', 'g', 'state.selected'), $.proxy(function (index, node) {
this.setSelectedState(node, false, options);
}, this));
}
node.state.selected = true;
if (!options.silent) {
this.$element.trigger('nodeSelected', $.extend(true, {}, node));
}
}
else {
node.state.selected = false;
if (!options.silent) {
this.$element.trigger('nodeUnselected', $.extend(true, {}, node));
}
}
};
Tree.prototype.toggleCheckedState = function (node, options) {
if (!node) return;
this.setCheckedState(node, !node.state.checked, options);
};
Tree.prototype.setCheckedState = function (node, state, options) {
if (state === node.state.checked) return;
if (state) {
node.state.checked = true;
if (!options.silent) {
this.$element.trigger('nodeChecked', $.extend(true, {}, node));
}
}
else {
node.state.checked = false;
if (!options.silent) {
this.$element.trigger('nodeUnchecked', $.extend(true, {}, node));
}
}
};
Tree.prototype.setDisabledState = function (node, state, options) {
if (state === node.state.disabled) return;
if (state) {
node.state.disabled = true;
this.setExpandedState(node, false, options);
this.setSelectedState(node, false, options);
this.setCheckedState(node, false, options);
if (!options.silent) {
this.$element.trigger('nodeDisabled', $.extend(true, {}, node));
}
}
else {
node.state.disabled = false;
if (!options.silent) {
this.$element.trigger('nodeEnabled', $.extend(true, {}, node));
}
}
};
Tree.prototype.render = function () {
if (!this.initialized) {
this.$element.addClass(pluginName);
this.$wrapper = $(this.template.list);
this.injectStyle();
this.initialized = true;
}
this.$element.empty().append(this.$wrapper.empty());
this.buildTree(this.tree, 0);
};
Tree.prototype.buildTree = function (nodes, level) {
if (!nodes) return;
level += 1;
var _this = this;
$.each(nodes, function addNodes(id, node) {
var treeItem = $(_this.template.item)
.addClass('node-' + _this.elementId)
.addClass(node.state.checked ? 'node-checked' : '')
.addClass(node.state.disabled ? 'node-disabled': '')
.addClass(node.state.selected ? 'node-selected' : '')
.addClass(node.searchResult ? 'search-result' : '')
.attr('data-nodeid', node.nodeId)
.attr('style', _this.buildStyleOverride(node));
for (var i = 0; i < (level - 1); i++) {
treeItem.append(_this.template.indent);
}
var classList = [];
if (node.nodes) {
classList.push('expand-icon');
if (node.state.expanded) {
classList.push(_this.options.collapseIcon);
}
else {
classList.push(_this.options.expandIcon);
}
}
else {
classList.push(_this.options.emptyIcon);
}
treeItem
.append($(_this.template.icon)
.addClass(classList.join(' '))
);
if (_this.options.showIcon) {
var classList = ['node-icon'];
classList.push(node.icon || _this.options.nodeIcon);
if (node.state.selected) {
classList.pop();
classList.push(node.selectedIcon || _this.options.selectedIcon ||
node.icon || _this.options.nodeIcon);
}
treeItem
.append($(_this.template.icon)
.addClass(classList.join(' '))
);
}
if (_this.options.showCheckbox) {
var classList = ['check-icon'];
if (node.state.checked) {
classList.push(_this.options.checkedIcon);
}
else {
classList.push(_this.options.uncheckedIcon);
}
treeItem
.append($(_this.template.icon)
.addClass(classList.join(' '))
);
}
if (_this.options.enableLinks) {
treeItem
.append($(_this.template.link)
.attr('href', node.href)
.append(node.text)
);
}
else {
treeItem
.append(node.text);
}
if (_this.options.showTags && node.tags) {
$.each(node.tags, function addTag(id, tag) {
treeItem
.append($(_this.template.badge)
.append(tag)
);
});
}
_this.$wrapper.append(treeItem);
if (node.nodes && node.state.expanded && !node.state.disabled) {
return _this.buildTree(node.nodes, level);
}
});
};
Tree.prototype.buildStyleOverride = function (node) {
if (node.state.disabled) return '';
var color = node.color;
var backColor = node.backColor;
if (this.options.highlightSelected && node.state.selected) {
if (this.options.selectedColor) {
color = this.options.selectedColor;
}
if (this.options.selectedBackColor) {
backColor = this.options.selectedBackColor;
}
}
if (this.options.highlightSearchResults && node.searchResult && !node.state.disabled) {
if (this.options.searchResultColor) {
color = this.options.searchResultColor;
}
if (this.options.searchResultBackColor) {
backColor = this.options.searchResultBackColor;
}
}
return 'color:' + color +
';background-color:' + backColor + ';';
};
Tree.prototype.injectStyle = function () {
if (this.options.injectStyle && !document.getElementById(this.styleId)) {
$('').appendTo('head');
}
};
Tree.prototype.buildStyle = function () {
var style = '.node-' + this.elementId + '{';
if (this.options.color) {
style += 'color:' + this.options.color + ';';
}
if (this.options.backColor) {
style += 'background-color:' + this.options.backColor + ';';
}
if (!this.options.showBorder) {
style += 'border:none;';
}
else if (this.options.borderColor) {
style += 'border:1px solid ' + this.options.borderColor + ';';
}
style += '}';
if (this.options.onhoverColor) {
style += '.node-' + this.elementId + ':not(.node-disabled):hover{' +
'background-color:' + this.options.onhoverColor + ';' +
'}';
}
return this.css + style;
};
Tree.prototype.template = {
list: '
',
item: '',
indent: '',
icon: '',
link: '',
badge: ''
};
Tree.prototype.css = '.treeview .list-group-item{cursor:pointer}.treeview span.indent{margin-left:10px;margin-right:10px}.treeview span.icon{width:12px;margin-right:5px}.treeview .node-disabled{color:silver;cursor:not-allowed}'
/**
Returns a single node object that matches the given node id.
@param {Number} nodeId - A node's unique identifier
@return {Object} node - Matching node
*/
Tree.prototype.getNode = function (nodeId) {
return this.nodes[nodeId];
};
/**
Returns the parent node of a given node, if valid otherwise returns undefined.
@param {Object|Number} identifier - A valid node or node id
@returns {Object} node - The parent node
*/
Tree.prototype.getParent = function (identifier) {
var node = this.identifyNode(identifier);
return this.nodes[node.parentId];
};
/**
Returns an array of sibling nodes for a given node, if valid otherwise returns undefined.
@param {Object|Number} identifier - A valid node or node id
@returns {Array} nodes - Sibling nodes
*/
Tree.prototype.getSiblings = function (identifier) {
var node = this.identifyNode(identifier);
var parent = this.getParent(node);
var nodes = parent ? parent.nodes : this.tree;
return nodes.filter(function (obj) {
return obj.nodeId !== node.nodeId;
});
};
/**
Returns an array of selected nodes.
@returns {Array} nodes - Selected nodes
*/
Tree.prototype.getSelected = function () {
return this.findNodes('true', 'g', 'state.selected');
};
/**
Returns an array of unselected nodes.
@returns {Array} nodes - Unselected nodes
*/
Tree.prototype.getUnselected = function () {
return this.findNodes('false', 'g', 'state.selected');
};
/**
Returns an array of expanded nodes.
@returns {Array} nodes - Expanded nodes
*/
Tree.prototype.getExpanded = function () {
return this.findNodes('true', 'g', 'state.expanded');
};
/**
Returns an array of collapsed nodes.
@returns {Array} nodes - Collapsed nodes
*/
Tree.prototype.getCollapsed = function () {
return this.findNodes('false', 'g', 'state.expanded');
};
/**
Returns an array of checked nodes.
@returns {Array} nodes - Checked nodes
*/
Tree.prototype.getChecked = function () {
return this.findNodes('true', 'g', 'state.checked');
};
/**
Returns an array of unchecked nodes.
@returns {Array} nodes - Unchecked nodes
*/
Tree.prototype.getUnchecked = function () {
return this.findNodes('false', 'g', 'state.checked');
};
/**
Returns an array of disabled nodes.
@returns {Array} nodes - Disabled nodes
*/
Tree.prototype.getDisabled = function () {
return this.findNodes('true', 'g', 'state.disabled');
};
/**
Returns an array of enabled nodes.
@returns {Array} nodes - Enabled nodes
*/
Tree.prototype.getEnabled = function () {
return this.findNodes('false', 'g', 'state.disabled');
};
/**
Set a node state to selected
@param {Object|Number} identifiers - A valid node, node id or array of node identifiers
@param {optional Object} options
*/
Tree.prototype.selectNode = function (identifiers, options) {
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
this.setSelectedState(node, true, options);
}, this));
this.render();
};
/**
Set a node state to unselected
@param {Object|Number} identifiers - A valid node, node id or array of node identifiers
@param {optional Object} options
*/
Tree.prototype.unselectNode = function (identifiers, options) {
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
this.setSelectedState(node, false, options);
}, this));
this.render();
};
/**
Toggles a node selected state; selecting if unselected, unselecting if selected.
@param {Object|Number} identifiers - A valid node, node id or array of node identifiers
@param {optional Object} options
*/
Tree.prototype.toggleNodeSelected = function (identifiers, options) {
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
this.toggleSelectedState(node, options);
}, this));
this.render();
};
/**
Collapse all tree nodes
@param {optional Object} options
*/
Tree.prototype.collapseAll = function (options) {
var identifiers = this.findNodes('true', 'g', 'state.expanded');
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
this.setExpandedState(node, false, options);
}, this));
this.render();
};
/**
Collapse a given tree node
@param {Object|Number} identifiers - A valid node, node id or array of node identifiers
@param {optional Object} options
*/
Tree.prototype.collapseNode = function (identifiers, options) {
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
this.setExpandedState(node, false, options);
}, this));
this.render();
};
/**
Expand all tree nodes
@param {optional Object} options
*/
Tree.prototype.expandAll = function (options) {
options = $.extend({}, _default.options, options);
if (options && options.levels) {
this.expandLevels(this.tree, options.levels, options);
}
else {
var identifiers = this.findNodes('false', 'g', 'state.expanded');
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
this.setExpandedState(node, true, options);
}, this));
}
this.render();
};
/**
Expand a given tree node
@param {Object|Number} identifiers - A valid node, node id or array of node identifiers
@param {optional Object} options
*/
Tree.prototype.expandNode = function (identifiers, options) {
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
this.setExpandedState(node, true, options);
if (node.nodes && (options && options.levels)) {
this.expandLevels(node.nodes, options.levels-1, options);
}
}, this));
this.render();
};
Tree.prototype.expandLevels = function (nodes, level, options) {
options = $.extend({}, _default.options, options);
$.each(nodes, $.proxy(function (index, node) {
this.setExpandedState(node, (level > 0) ? true : false, options);
if (node.nodes) {
this.expandLevels(node.nodes, level-1, options);
}
}, this));
};
/**
Reveals a given tree node, expanding the tree from node to root.
@param {Object|Number|Array} identifiers - A valid node, node id or array of node identifiers
@param {optional Object} options
*/
Tree.prototype.revealNode = function (identifiers, options) {
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
var parentNode = this.getParent(node);
while (parentNode) {
this.setExpandedState(parentNode, true, options);
parentNode = this.getParent(parentNode);
};
}, this));
this.render();
};
/**
Toggles a nodes expanded state; collapsing if expanded, expanding if collapsed.
@param {Object|Number} identifiers - A valid node, node id or array of node identifiers
@param {optional Object} options
*/
Tree.prototype.toggleNodeExpanded = function (identifiers, options) {
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
this.toggleExpandedState(node, options);
}, this));
this.render();
};
/**
Check all tree nodes
@param {optional Object} options
*/
Tree.prototype.checkAll = function (options) {
var identifiers = this.findNodes('false', 'g', 'state.checked');
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
this.setCheckedState(node, true, options);
}, this));
this.render();
};
/**
Check a given tree node
@param {Object|Number} identifiers - A valid node, node id or array of node identifiers
@param {optional Object} options
*/
Tree.prototype.checkNode = function (identifiers, options) {
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
this.setCheckedState(node, true, options);
}, this));
this.render();
};
/**
Uncheck all tree nodes
@param {optional Object} options
*/
Tree.prototype.uncheckAll = function (options) {
var identifiers = this.findNodes('true', 'g', 'state.checked');
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
this.setCheckedState(node, false, options);
}, this));
this.render();
};
/**
Uncheck a given tree node
@param {Object|Number} identifiers - A valid node, node id or array of node identifiers
@param {optional Object} options
*/
Tree.prototype.uncheckNode = function (identifiers, options) {
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
this.setCheckedState(node, false, options);
}, this));
this.render();
};
/**
Toggles a nodes checked state; checking if unchecked, unchecking if checked.
@param {Object|Number} identifiers - A valid node, node id or array of node identifiers
@param {optional Object} options
*/
Tree.prototype.toggleNodeChecked = function (identifiers, options) {
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
this.toggleCheckedState(node, options);
}, this));
this.render();
};
/**
Disable all tree nodes
@param {optional Object} options
*/
Tree.prototype.disableAll = function (options) {
var identifiers = this.findNodes('false', 'g', 'state.disabled');
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
this.setDisabledState(node, true, options);
}, this));
this.render();
};
/**
Disable a given tree node
@param {Object|Number} identifiers - A valid node, node id or array of node identifiers
@param {optional Object} options
*/
Tree.prototype.disableNode = function (identifiers, options) {
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
this.setDisabledState(node, true, options);
}, this));
this.render();
};
/**
Enable all tree nodes
@param {optional Object} options
*/
Tree.prototype.enableAll = function (options) {
var identifiers = this.findNodes('true', 'g', 'state.disabled');
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
this.setDisabledState(node, false, options);
}, this));
this.render();
};
/**
Enable a given tree node
@param {Object|Number} identifiers - A valid node, node id or array of node identifiers
@param {optional Object} options
*/
Tree.prototype.enableNode = function (identifiers, options) {
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
this.setDisabledState(node, false, options);
}, this));
this.render();
};
/**
Toggles a nodes disabled state; disabling is enabled, enabling if disabled.
@param {Object|Number} identifiers - A valid node, node id or array of node identifiers
@param {optional Object} options
*/
Tree.prototype.toggleNodeDisabled = function (identifiers, options) {
this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
this.setDisabledState(node, !node.state.disabled, options);
}, this));
this.render();
};
/**
Common code for processing multiple identifiers
*/
Tree.prototype.forEachIdentifier = function (identifiers, options, callback) {
options = $.extend({}, _default.options, options);
if (!(identifiers instanceof Array)) {
identifiers = [identifiers];
}
$.each(identifiers, $.proxy(function (index, identifier) {
callback(this.identifyNode(identifier), options);
}, this));
};
/*
Identifies a node from either a node id or object
*/
Tree.prototype.identifyNode = function (identifier) {
return ((typeof identifier) === 'number') ?
this.nodes[identifier] :
identifier;
};
/**
Searches the tree for nodes (text) that match given criteria
@param {String} pattern - A given string to match against
@param {optional Object} options - Search criteria options
@return {Array} nodes - Matching nodes
*/
Tree.prototype.search = function (pattern, options) {
options = $.extend({}, _default.searchOptions, options);
this.clearSearch({ render: false });
var results = [];
if (pattern && pattern.length > 0) {
if (options.exactMatch) {
pattern = '^' + pattern + '$';
}
var modifier = 'g';
if (options.ignoreCase) {
modifier += 'i';
}
results = this.findNodes(pattern, modifier);
$.each(results, function (index, node) {
node.searchResult = true;
})
}
if (options.revealResults) {
this.revealNode(results);
}
else {
this.render();
}
this.$element.trigger('searchComplete', $.extend(true, {}, results));
return results;
};
/**
Clears previous search results
*/
Tree.prototype.clearSearch = function (options) {
options = $.extend({}, { render: true }, options);
var results = $.each(this.findNodes('true', 'g', 'searchResult'), function (index, node) {
node.searchResult = false;
});
if (options.render) {
this.render();
}
this.$element.trigger('searchCleared', $.extend(true, {}, results));
};
/**
Find nodes that match a given criteria
@param {String} pattern - A given string to match against
@param {optional String} modifier - Valid RegEx modifiers
@param {optional String} attribute - Attribute to compare pattern against
@return {Array} nodes - Nodes that match your criteria
*/
Tree.prototype.findNodes = function (pattern, modifier, attribute) {
modifier = modifier || 'g';
attribute = attribute || 'text';
var _this = this;
return $.grep(this.nodes, function (node) {
var val = _this.getNodeValue(node, attribute);
if (typeof val === 'string') {
return val.match(new RegExp(pattern, modifier));
}
});
};
/**
Recursive find for retrieving nested attributes values
All values are return as strings, unless invalid
@param {Object} obj - Typically a node, could be any object
@param {String} attr - Identifies an object property using dot notation
@return {String} value - Matching attributes string representation
*/
Tree.prototype.getNodeValue = function (obj, attr) {
var index = attr.indexOf('.');
if (index > 0) {
var _obj = obj[attr.substring(0, index)];
var _attr = attr.substring(index + 1, attr.length);
return this.getNodeValue(_obj, _attr);
}
else {
if (obj.hasOwnProperty(attr)) {
return obj[attr].toString();
}
else {
return undefined;
}
}
};
var logError = function (message) {
if (window.console) {
window.console.error(message);
}
};
$.fn[pluginName] = function (options, args) {
var result;
this.each(function () {
var _this = $.data(this, pluginName);
if (typeof options === 'string') {
if (!_this) {
logError('Not initialized, can not call method : ' + options);
}
else if (!$.isFunction(_this[options]) || options.charAt(0) === '_') {
logError('No such method : ' + options);
}
else {
if (!(args instanceof Array)) {
args = [ args ];
}
result = _this[options].apply(_this, args);
}
}
else if (typeof options === 'boolean') {
result = _this;
}
else {
$.data(this, pluginName, new Tree(this, $.extend(true, {}, options)));
}
});
return result || this;
};
})(jQuery, window, document);/*! version : 4.17.47
=========================================================
bootstrap-datetimejs
https://github.com/Eonasdan/bootstrap-datetimepicker
Copyright (c) 2015 Jonathan Peterson
=========================================================
*/
/*
The MIT License (MIT)
Copyright (c) 2015 Jonathan Peterson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/*global define:false */
/*global exports:false */
/*global require:false */
/*global jQuery:false */
/*global moment:false */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(['jquery', 'moment'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('jquery'), require('moment'));
} else {
if (typeof jQuery === 'undefined') {
throw 'bootstrap-datetimepicker requires jQuery to be loaded first';
}
if (typeof moment === 'undefined') {
throw 'bootstrap-datetimepicker requires Moment.js to be loaded first';
}
factory(jQuery, moment);
}
}(function ($, moment) {
'use strict';
if (!moment) {
throw new Error('bootstrap-datetimepicker requires Moment.js to be loaded first');
}
var dateTimePicker = function (element, options) {
var picker = {},
date,
viewDate,
unset = true,
input,
component = false,
widget = false,
use24Hours,
minViewModeNumber = 0,
actualFormat,
parseFormats,
currentViewMode,
datePickerModes = [
{
clsName: 'days',
navFnc: 'M',
navStep: 1
},
{
clsName: 'months',
navFnc: 'y',
navStep: 1
},
{
clsName: 'years',
navFnc: 'y',
navStep: 10
},
{
clsName: 'decades',
navFnc: 'y',
navStep: 100
}
],
viewModes = ['days', 'months', 'years', 'decades'],
verticalModes = ['top', 'bottom', 'auto'],
horizontalModes = ['left', 'right', 'auto'],
toolbarPlacements = ['default', 'top', 'bottom'],
keyMap = {
'up': 38,
38: 'up',
'down': 40,
40: 'down',
'left': 37,
37: 'left',
'right': 39,
39: 'right',
'tab': 9,
9: 'tab',
'escape': 27,
27: 'escape',
'enter': 13,
13: 'enter',
'pageUp': 33,
33: 'pageUp',
'pageDown': 34,
34: 'pageDown',
'shift': 16,
16: 'shift',
'control': 17,
17: 'control',
'space': 32,
32: 'space',
't': 84,
84: 't',
'delete': 46,
46: 'delete'
},
keyState = {},
/********************************************************************************
*
* Private functions
*
********************************************************************************/
hasTimeZone = function () {
return moment.tz !== undefined && options.timeZone !== undefined && options.timeZone !== null && options.timeZone !== '';
},
getMoment = function (d) {
var returnMoment;
if (d === undefined || d === null) {
returnMoment = moment(); //TODO should this use format? and locale?
} else if (moment.isDate(d) || moment.isMoment(d)) {
returnMoment = moment(d);
} else if (hasTimeZone()) { // There is a string to parse and a default time zone
returnMoment = moment.tz(d, parseFormats, options.useStrict, options.timeZone);
} else {
returnMoment = moment(d, parseFormats, options.useStrict);
}
if (hasTimeZone()) {
returnMoment.tz(options.timeZone);
}
return returnMoment;
},
isEnabled = function (granularity) {
if (typeof granularity !== 'string' || granularity.length > 1) {
throw new TypeError('isEnabled expects a single character string parameter');
}
switch (granularity) {
case 'y':
return actualFormat.indexOf('Y') !== -1;
case 'M':
return actualFormat.indexOf('M') !== -1;
case 'd':
return actualFormat.toLowerCase().indexOf('d') !== -1;
case 'h':
case 'H':
return actualFormat.toLowerCase().indexOf('h') !== -1;
case 'm':
return actualFormat.indexOf('m') !== -1;
case 's':
return actualFormat.indexOf('s') !== -1;
default:
return false;
}
},
hasTime = function () {
return (isEnabled('h') || isEnabled('m') || isEnabled('s'));
},
hasDate = function () {
return (isEnabled('y') || isEnabled('M') || isEnabled('d'));
},
getDatePickerTemplate = function () {
var headTemplate = $('')
.append($('